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 pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# Data Preparation
penguins_df = pd.read_csv("penguins.csv")
penguins_dummy = pd.get_dummies(penguins_df, drop_first=True)
# Data Preprocessing
penguins_scaled = StandardScaler().fit_transform(penguins_dummy)
# Checking for optimal cluster count through elbow method
inertia = []
for k in range(1, 10):
model = KMeans(n_clusters=k).fit(penguins_scaled)
inertia.append(model.inertia_)
plt.plot(range(1, 10), inertia)
plt.title("Elbow Analysis")
plt.annotate(text="Optimal", xy=(3, 600), xytext=(3, 800), arrowprops=dict(facecolor='red', shrink=0.01))
plt.show()
# It seems 3 is the most optimal
# Model creation
model = KMeans(n_clusters=3).fit(penguins_scaled)
labels = model.predict(penguins_scaled)
plt.scatter(penguins_df['body_mass_g'], penguins_df['flipper_length_mm'], c=labels)
plt.title("KMeans Clustering of Penguins")
plt.show()
# Summary Finalization
penguins_df['label'] = labels
num_cols = [col for col in penguins_df.columns if col != 'sex']
stat_penguins = pd.DataFrame(penguins_df.groupby('label')[num_cols].mean())
stat_penguins