source: @allison_horst https://github.com/allisonhorst/penguins
1. Project Overview
This project aims to identify potential groups (clusters) among penguins based on their physical measurements. The data, collected from Palmer Station, Antarctica, lacks species labels, so unsupervised learning (clustering) is used to group the penguins.
A team of researchers 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.
2. Importing Required Libraries
# Import Required Packages
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler3. Load and Explore the Dataset
# Load data from CSV and inspect structure, missing values, and types
penguins_df = pd.read_csv("penguins.csv")
print(penguins_df.head())
print(penguins_df.isna().sum())
print(penguins_df.info())4. Encode Categorical Variables
# Convert 'sex' to dummy variables for machine learning compatibility
penguins_df=pd.get_dummies(penguins_df,columns=["sex"])
print(penguins_df.head(5))
print(penguins_df.info())5. Feature Scaling
# Standardize all features for clustering using StandardScaler
scaler=StandardScaler()
X=scaler.fit_transform(penguins_df)print(X)6. Elbow Method to Determine Optimal Clusters
# Try K values from 1 to 9 and store inertia to find the best number of clusters
inertia=[]
for k in range(1,10):
kmeans=KMeans(n_clusters=k,random_state=42).fit(X)
inertia.append(kmeans.inertia_)
print(inertia)
print(kmeans.labels_)plt.plot(range(1,10),inertia,marker='o')
plt.show()