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()# Create dummy variables for "sex" column using get dummies method
penguins_encoded = pd.get_dummies(penguins_df, columns=["sex"], drop_first=True)
# Standardize the encoded dataset
scaler = StandardScaler()
penguins_scaled = scaler.fit_transform(penguins_encoded)
# Perform Elbow analysis to determine the optimal number of clusters
inertia = []
for k in range(1, 10):
kmeans = KMeans(n_clusters=k, random_state=42)
kmeans.fit(penguins_scaled)
inertia.append(kmeans.inertia_)
# Visualize the inertia
plt.plot(range(1, 10), inertia)
plt.xlabel('Number of Clusters')
plt.ylabel('Inertia')
plt.title('Elbow Method For Optimal k')
plt.grid(True)
plt.show()# Based on the Elbow analysis, determine the optimal number of clusters
optimal_k = 4
# Perform KMeans clustering with the optimal number of clusters
kmeans_final = KMeans(n_clusters=optimal_k, random_state=42)
kmeans_final.fit(penguins_scaled)
# Create a DataFrame to store cluster characteristics
numeric_columns = penguins_df.drop(columns="sex")
numeric_columns["label"] = kmeans_final.labels_
# Calculate the mean of numeric columns for each cluster
stat_penguins = numeric_columns.groupby('label').mean()
# Print the final characteristic table
print(stat_penguins)