Skip to content
Hierarchical: 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
import seaborn as sns
from scipy.cluster.hierarchy import linkage, fcluster, dendrogram
from scipy.cluster.vq import whiten
# Loading and examining the dataset
penguins_df = pd.read_csv("penguins.csv")
penguins_df.head()
# view columns
penguins_df.info()
# Get dummy variables
penguins_df = pd.get_dummies(penguins_df, dtype='int')
print(penguins_df)
print(penguins_df.info())
# Exploring for variance
print(penguins_df.var())
# Normalize the data with whiten method
whitened_data = whiten(penguins_df.values)
# Convert normalized data to a DataFrame
penguins_norm = pd.DataFrame(whitened_data, columns=penguins_df.columns)
penguins_norm.describe()
# Create distance matrix
distance_matrix = linkage(penguins_norm, method='ward', metric = 'euclidean')
# Visualizing clusters with dendrogram
dn = dendrogram(distance_matrix)
plt.show()
# Assign cluster labels
penguins_norm['cluster_labels'] = fcluster(distance_matrix, 4, criterion='maxclust')
print(penguins_norm['cluster_labels'].value_counts())
# Visualize Clusters
plt.scatter(penguins_norm['cluster_labels'], penguins_norm['culmen_length_mm'], cmap='viridis')
plt.xlabel('Cluster')
plt.ylabel('culmen_length_mm')
plt.title(f'Hierarchical Clustering of Penguins')
plt.show()
# Stat_penguins DataFrame
numeric_columns = ['culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'label']
stat_penguins = penguins_df[numeric_columns].groupby('label').mean()
stat_penguins