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 numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
# Loading and examining the dataset
penguins_df = pd.read_csv("penguins.csv")
penguins_df.head()
# ----------------- preprocessing steps -----------------
gender_dummies = pd.get_dummies(penguins_df['sex'], drop_first=True)
penguins_df = penguins_df.join(gender_dummies)
penguins_df.drop('sex', axis=1, inplace=True)
print(penguins_df.head())
# ----------------- Detecting the best number of clusters -----------------
inertias = []
for k in range(1, 11):
scaler = StandardScaler()
kmeans = KMeans(n_clusters=k, random_state = 0)
pipeline = make_pipeline(scaler, kmeans)
pipeline.fit(penguins_df)
inertias.append(pipeline.named_steps['kmeans'].inertia_)
plt.plot(range(1,11), inertias)
plt.show()
# -------------- Running the k-means clustering algorithm --------------
scaler = StandardScaler()
kmeans = KMeans(n_clusters=4, random_state = 0)
pipeline = make_pipeline(scaler, kmeans)
pipeline.fit(penguins_df)
labels = pipeline.predict(penguins_df)
plt.scatter(penguins_df.iloc[:, 0], penguins_df.iloc[:, 1], c=labels)
plt.show()
# ----------------- Creating a final statistical DataFrame for each cluster -----------------
penguins_df['cluster'] = labels
stat_penguins = penguins_df.groupby('cluster').mean(numeric_only=True)
print(stat_penguins)