Skip to content

Alt text 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.

ColumnDescription
culmen_length_mmculmen length (mm)
culmen_depth_mmculmen depth (mm)
flipper_length_mmflipper length (mm)
body_mass_gbody mass (g)
sexpenguin 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.sex=penguins_df.sex.astype("category")
penguins_df["sex_codes"] = penguins_df.sex.cat.codes
penguins_df.head()
from sklearn.preprocessing import StandardScaler

X = penguins_df.select_dtypes("float")
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X) # numpy array
X_scaled_df = pd.DataFrame(X_scaled, columns=X.columns, index=X.index) # pandas df
X_scaled_df["sex_codes"] = penguins_df.sex_codes
X_scaled_df.head()
# Perform KMeans clustering with 3 clusters on X_scaled_df
kmeans = KMeans(n_clusters=3, random_state=42)
X_scaled_df["cluster"] = kmeans.fit_predict(X_scaled_df)
X_scaled_df.head()
penguins_df["cluster"] = X_scaled_df.cluster
stat_penguins = penguins_df.groupby("cluster", as_index=False).agg("mean")
stat_penguins
import seaborn as sns

# Use pairplot to visualize clusters in X_scaled_df
sns.pairplot(
    penguins_df,
    vars=["culmen_length_mm", "culmen_depth_mm", "flipper_length_mm", "body_mass_g"],
    hue="cluster",
    palette="Set1",
    diag_kind="kde",
    plot_kws={"alpha": 0.7}
)
plt.suptitle("Pairplot of Scaled Features Colored by Cluster", y=1.02)
plt.show()