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.metrics import silhouette_score
# Loading and examining the dataset
penguins_df = pd.read_csv("penguins.csv")
penguins_df = pd.get_dummies(penguins_df, dtype='int')
stat_penguins = StandardScaler().fit_transform(penguins_df)
# Convert the scaled data back to a DataFrame
stat_penguins = pd.DataFrame(scaled_penguins_df, columns=penguins_df.columns)
#determing the inertia of clusters
num_clusters = [i for i in range(3, 11)]
def num_cluster(num_clusters, x_val):
inertia = []
for num in num_clusters:
kmeans = KMeans(n_clusters=num, random_state=42)
kmeans.fit(x_val)
inertia.append(kmeans.inertia_)
return inertia
# determining the silhoutte score
def sil_score1(num_clusters, x_val):
sil_scores = []
for num in num_clusters:
kmeans = KMeans(n_clusters=num, random_state=42)
kmeans.fit(x_val)
sil_scores.append(silhouette_score(x_val, kmeans.labels_))
return sil_scores
# Compute inertia values
inertia = num_cluster(num_clusters,stat_penguins)
# Compute the silhoutte score values
sil_scores = sil_score1(num_clusters,stat_penguins)
# Plot the inertia results
plt.figure(figsize=(10, 6))
plt.plot(num_clusters, inertia, marker='o', color='blue')
plt.xlabel('Number Of Clusters')
plt.ylabel('Inertia')
plt.title('Elbow Method')
plt.show()
# Plot the silhouette score results
plt.figure(figsize=(10, 6))
plt.plot(num_clusters, sil_scores, marker='o', color='red')
plt.xlabel('Number Of Clusters')
plt.ylabel('Silhouette Score')
plt.title('Silhouette Score vs. Number of Clusters')
plt.show()
kmeans4 = KMeans(n_clusters = 4 , random_state= 42)
kmeans4.fit(stat_penguins)
print(kmeans4.labels_[:5])
print('Unique labels:', np.unique(kmeans4.labels_) )
penguins_df['label'] = kmeans4.labels_
#visulaize the cluster of data points for labels and culmen_length_mm
plt.scatter(penguins_df['label'], penguins_df['culmen_length_mm'], c= kmeans4.labels_, cmap='viridis')
plt.xlabel('Cluster')
plt.ylabel('culmen_length_mm')
plt.title(f'K-means Clustering (K={n_clusters})')
plt.show()
# create final data frame
numeric_columns = ['culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm','label']
stat_penguins= penguins_df[numeric_columns].groupby('label').mean()
stat_penguins.head()