Skip to content
Project: Interpreting Unsupervised Learning Models
Arctic Penguin Exploration: Unraveling Clusters in the Icy Domain with K-means clustering
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!
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.
- 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 three species that are native to the region: Adelie, Chinstrap, and Gentoo, so 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.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# Loading and examining the dataset
penguins_df = pd.read_csv("data/penguins.csv")
from sklearn.impute import SimpleImputer
# Perform K-means clustering
kmeans = KMeans(n_clusters=3, random_state=0)
# Impute missing values
imputer = SimpleImputer()
imputed_data = imputer.fit_transform(penguins_df[['culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'body_mass_g']])
# Fit K-means clustering on imputed data
kmeans.fit(imputed_data)
# Add cluster labels to the dataframe
penguins_df['cluster'] = kmeans.labels_
# Verify the algorithm quality
# Calculate the silhouette score
from sklearn.metrics import silhouette_score
# Calculate the silhouette score for the clustered data
silhouette_score = silhouette_score(imputed_data, kmeans.labels_)
# Print the silhouette score
print('Silhouette Score:', silhouette_score)
# The silhouette score measures the compactness and separation of the clusters.
# A score close to 1 indicates well-separated clusters,
# while a score close to -1 indicates overlapping clusters.
if silhouette_score > 0.5:
print('The silhouette score is good!')
else:
print('The silhouette score is not very good.')