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 seaborn as sns
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.isna().sum()
for i in penguins_df.columns:
if penguins_df[i].dtype in ['float64', 'int64']: # Plot only for numeric columns
sns.kdeplot(penguins_df[i])
plt.show()
penguins_df = pd.get_dummies(penguins_df, dtype='int')
scaler = StandardScaler()
scaled = scaler.fit_transform(penguins_df)
penguins_scaled = pd.DataFrame(data=scaled,columns=penguins_df.columns)
k_values = range(1, 11)
inertia = []
# Perform KMeans for each k and calculate inertia
for k in k_values:
kmeans = KMeans(n_clusters=k, random_state=42)
kmeans.fit(penguins_scaled)
inertia.append(kmeans.inertia_)
# Plot the inertia against the number of clusters
plt.figure(figsize=(10, 6))
plt.plot(k_values, inertia, 'bo-')
plt.xlabel('Number of clusters (k)')
plt.ylabel('Inertia')
plt.title('Elbow Method For Optimal k')
plt.xticks(k_values)
plt.grid(True)
plt.show()
kmeans = KMeans(n_clusters=4, random_state=42).fit(penguins_scaled)
penguins_df['label'] = kmeans.labels_
plt.scatter(penguins_df['label'], penguins_df['culmen_length_mm'], c=kmeans.labels_, cmap='viridis')
plt.xlabel('Cluster')
plt.ylabel('culmen_length_mm')
plt.xticks(range(int(penguins_df['label'].min()), int(penguins_df['label'].max()) + 1))
plt.title(f'K-means Clustering (K={4})')
plt.show()
numeric_columns = ['culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm','label']
stat_penguins = penguins_df[numeric_columns].groupby('label').mean()
stat_penguins