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 = pd.get_dummies(penguins_df, columns=['sex'])
# Scaling features
features_to_scale = penguins_df[['culmen_length_mm',
'culmen_depth_mm',
'flipper_length_mm',
'body_mass_g']]
scaler = StandardScaler()
scaled_features = scaler.fit_transform(features_to_scale)
scaled_features_df = pd.DataFrame(scaled_features, columns=features_to_scale.columns)
scaled_df = pd.concat([penguins_df.drop(columns=features_to_scale.columns),
scaled_features_df], axis=1)
scaled_df.head()# Performing elbow analysis using scaled_df
inertia = []
k_values = list(range(1, 10))
for k in k_values:
kmeans = KMeans(n_clusters=k, random_state=42).fit(scaled_df)
inertia.append(kmeans.inertia_)
# Plotting Elbow analysis
plt.figure(figsize=(10, 6))
plt.plot(k_values, inertia, marker='o')
plt.title("Elbow Analysis")
plt.xlabel("Number of Clusters (k)")
plt.ylabel("Inertia")
plt.grid()
plt.show()# Performing clustering using results of Elbow analysis
kmeans = KMeans(n_clusters=3, random_state=42).fit(scaled_df)
labels = kmeans.labels_
# Plotting the clusters
plt.scatter(penguins_df['culmen_depth_mm'],
penguins_df['body_mass_g'],
c=labels,
alpha=0.6,
edgecolors='w')
plt.title('Scatter Plot of Penguin Clusters')
plt.xlabel('Culmen Depth (mm)')
plt.ylabel('Body Mass (g)')
plt.grid()
plt.show()# Creating statistical dataframe for submission
numeric_columns = ['culmen_length_mm',
'culmen_depth_mm',
'flipper_length_mm',
'body_mass_g']
penguins_df['label'] = labels
stat_penguins = penguins_df.groupby('label')[numeric_columns].mean()
stat_penguins.head()