Skip to content
Project: Clustering Antarctic Penguin Species
source: @allison_horst https://github.com/allisonhorst/penguins
You have been asked to support a team of researchers who have been collecting data about penguins in Antartica! The data is available in csv-Format as penguins.csv
Origin of this data : Data were collected and made available by Dr. Kristen Gorman and the Palmer Station, Antarctica LTER, a member of the Long Term Ecological Research Network.
The dataset consists of 5 columns.
| Column | Description |
|---|---|
| culmen_length_mm | culmen length (mm) |
| culmen_depth_mm | culmen depth (mm) |
| flipper_length_mm | flipper length (mm) |
| body_mass_g | body mass (g) |
| sex | penguin sex |
Unfortunately, they have not been able to record the species of penguin, but they know that there are at least three species that are native to the region: Adelie, Chinstrap, and Gentoo. Your task is to apply your data science skills to help them identify groups in the dataset!
# Import Required Packages
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# Loading and examining the dataset
penguins_df = pd.read_csv("penguins.csv")
penguins_df.head()penguins_df.info()
#create dummy variables because machine learning works with numerical values
penguins_df = pd.get_dummies(penguins_df,columns = ["sex"],drop_first=True)
penguins_df.head()from sklearn.preprocessing import StandardScaler
# the predicted values
scaler = StandardScaler()
scaled = scaler.fit_transform(penguins_df) # I am not predicting, I am clustering#performing elblow analysis to determine the number of clusters to
#elbow analysis is used on the original data not preprocessed data
inertia = []# inertia determine how close the clusters are in k_means
ks = range(1,12)
for i in ks: # random list of intertia
kmeans= KMeans(n_clusters=i,random_state=42).fit(penguins_df)#perform k_means
inertia.append(kmeans.inertia_)# get the inertia values
plt.plot(ks,inertia, '-o')#plot them
plt.xlabel("Number of Samples")
plt.ylabel("Inertia")
plt.title("A plot of to determine the optimal number of clusters")
plt.xticks(ks)
plt.show()
model = KMeans(n_clusters=3) # from the above the optimal is 3
labels = model.fit_predict(scaled)
# print(label)
df = pd.DataFrame({
"labels": labels,
"culmen_depth_mm": penguins_df["culmen_depth_mm"]
})
plt.scatter(df["labels"], df["culmen_depth_mm"], c=model.labels_)
plt.title("A plot to show the different varietis of penguins")
plt.show()penguins_df.columns
numeric_columns = ['culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm',
'body_mass_g'] # lables and their mean
penguins_df["label"] = model.labels_
stat_penguins = penguins_df.groupby("label")[numeric_columns].mean()
stat_penguinspenguins_df.head(20)