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 numpy as np
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()# Preprocessing steps for getting dummy data
penguins_df = pd.get_dummies(penguins_df, drop_first=True, dtype='int')
scaler = StandardScaler().fit_transform(penguins_df)
penguins_preprocessed = pd.DataFrame(data=scaler,columns=penguins_df.columns)
print(penguins_preprocessed)
penguins_df# elbow plot
inertia = []
for i in range(1, 10):
kmeans = KMeans(n_clusters=i, random_state=42).fit(penguins_preprocessed)
inertia.append(kmeans.inertia_)
plt.plot(range(1, 10), inertia, 'o')
plt.xlabel('number of clusters, k')
plt.ylabel('inertia')
plt.xticks(inertia)
plt.title('elbow method')
plt.show()
n_clusters = 4# kmeans algorithm
kmeans = KMeans(n_clusters = n_clusters, random_state=42).fit(penguins_preprocessed)
labels = kmeans.predict(penguins_preprocessed)
penguins_df['label'] = labels
print(penguins_df)
df = pd.DataFrame()
plt.scatter(penguins_df['label'], penguins_df['culmen_length_mm'], c=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.show()# final statistical Dataframe
numeric_columns = penguins_df.columns.to_numpy()
stat_penguins = penguins_df.groupby('label')[numeric_columns].mean()
stat_penguins