Skip to content

Arctic Penguin Exploration: Unraveling Clusters in the Icy Domain with K-means clustering

Alt text 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")
def clean_data(df):       
    for col in df.columns:
            if (df[col].isnull().sum() > 0) and (df[col].dtype =="float64"):
                mean=df[col].mean()
                df[col]=df[col].fillna(mean)
            elif(df[col].isnull().sum() > 0) and (df[col].dtype =="object"):
                mode=df[col].mode()[0]
                df[col]=df[col].fillna(mode)
    return df
penguins_clean=clean_data(penguins_df)
penguins_clean=penguins_clean.drop([9,14])
penguins_clean=pd.get_dummies(penguins_clean,drop_first=True)
scaler=StandardScaler()
penguins_preprocessed=scaler.fit_transform(penguins_clean.values)
pca=PCA()
pca.fit(penguins_preprocessed)
transforms=pca.transform(penguins_preprocessed)
n_components=pca.n_components_
pca=PCA(n_components=6)
pca.fit(penguins_preprocessed)
penguins_PCA=pca.transform(penguins_preprocessed)
inertia=[]
cluster=[]
for i in range(1,11):
    kmeans=KMeans(n_clusters=i,random_state=42)
    kmeans.fit(penguins_preprocessed)
    inertia.append(kmeans.inertia_)
    cluster.append(i)
plt.plot(cluster,inertia)
plt.show()
xs=penguins_PCA[:,0]
ys=penguins_PCA[:,1]
n_cluster=4
kmeans=KMeans(n_clusters=n_cluster,random_state=42)
kmeans.fit(penguins_preprocessed)
 
plt.scatter(xs,ys,c=kmeans.labels_)
plt.xlabel("first_pca_component")
plt.ylabel("second_pca_component")
plt.title(f"k-means  clustering by {n_cluster} clusters.")
plt.show()