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
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
import plotly.graph_objects as go
# Loading and examining the dataset
penguins_df = pd.read_csv("penguins.csv")
penguins_df.head()penguins_df.info()penguins_df.isnull().sum()preprocess = ColumnTransformer(
transformers = [
("num", StandardScaler(), ["culmen_length_mm", "culmen_depth_mm", "flipper_length_mm", "body_mass_g"]),
("cat", OneHotEncoder(), ["sex"])
]
)
model = Pipeline(steps = [
("preprocess", preprocess),
("cluster", KMeans(n_clusters = 3, random_state = 42))
])model.fit(penguins_df)labels = model.named_steps["cluster"].labels_
penguins_df["clusters"] = labels
penguins_df["clusters"].value_counts()colors = ['#e8000b', '#1ac938', '#023eff']
cluster_0 = penguins_df[penguins_df['clusters']==0]
cluster_1 = penguins_df[penguins_df['clusters']==1]
cluster_2 = penguins_df[penguins_df['clusters']==2]from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize =(10,7))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(cluster_0['culmen_length_mm'],
cluster_0['culmen_depth_mm'],
cluster_0['flipper_length_mm'],
c = colors[0], label = "Cluster 0"
)
ax.scatter(cluster_1['culmen_length_mm'],
cluster_1['culmen_depth_mm'],
cluster_1['flipper_length_mm'],
c = colors[1], label = "Cluster 1"
)
ax.scatter(cluster_2['culmen_length_mm'],
cluster_2['culmen_depth_mm'],
cluster_2['flipper_length_mm'],
c = colors[2], label = "Cluster 2"
)
ax.set_xlabel("culmen_length (mm)")
ax.set_ylabel("culmen_depth (mm)")
ax.set_zlabel("flipper_length (mm)")
plt.legend()
plt.show()penguins_df
stat_penguins = penguins_df.groupby("clusters")["culmen_length_mm", "culmen_depth_mm", "flipper_length_mm", "body_mass_g"].mean().reset_index()stat_penguins