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.preprocessing import StandardScaler
from sklearn.cluster import KMeans
# Loading and examining the dataset
penguins_df = pd.read_csv('penguins.csv')
penguins_df.head()penguins_df.info()1 - Perform preprocessing steps on the dataset to create dummy variables
# Using get dummies method on the categorical feature
penguins_df = pd.get_dummies(penguins_df, drop_first=True)
penguins_df.head()# Standardizing/scaling before clustering
scaler = StandardScaler()
X = scaler.fit_transform(penguins_df.drop(columns='sex_MALE'))
type(X)print(X[:10])df = pd.DataFrame(X, columns=penguins_df.drop(columns='sex_MALE').columns)
df.head()penguins_preprocessed = pd.concat([df, penguins_df['sex_MALE']], axis=1)
penguins_preprocessed.head()2 - Detect the optimal number of clusters for k-means clustering
# Perform Elbow analysis
ks = range(1,10)
inertias = []
for k in ks:
model = KMeans(n_clusters=k, random_state=42)
model.fit(penguins_preprocessed)
inertias.append(model.inertia_)
print(inertias)# Visualize the list of inertias
plt.plot(ks, inertias, '-o')
plt.xlabel('number of clusters, k')
plt.ylabel('inertia')
plt.title('Elbow Analysis/Method')
plt.xticks(ks)
plt.show()# Optimal number of clusters - least number of clusters with lowest inertia
n_clusters = 43 - Run the k-means clustering algorithm