Skip to content

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! 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.

ColumnDescription
culmen_length_mmculmen length (mm)
culmen_depth_mmculmen depth (mm)
flipper_length_mmflipper length (mm)
body_mass_gbody mass (g)
sexpenguin 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

# Loading and examining the dataset
df = pd.read_csv("penguins.csv")
df.head()
#adding dummy variables

df=pd.get_dummies(df,columns=["sex"],drop_first=True)
df.head()
#Standardizing the dataset

scaler=StandardScaler()
sc=scaler.fit_transform(df)
df_scaled=pd.DataFrame(sc,columns=df.columns)
df_scaled.head()
#Performing Elbow analysis

inertia=[]
for i in range(1,11,1):
    km=KMeans(n_clusters=i,random_state=42).fit(df_scaled)
    inertia.append(km.inertia_)
# Plotting inertia values to determine the optimal number of clusters for the dataset

plt.plot(inertia)
plt.title("inertia values for each number of cluster")
# training the model using best inertia value which is 5
Kn=KMeans(n_clusters=5,random_state=42).fit(df_scaled)
labels=Kn.labels_
labels
#creatning a scatterplot of the labels vs culmen_length_mm
plt.scatter(labels,penguins_df['culmen_length_mm'])
plt.title("labels vs culmen_length_mm")
plt.xlabel("labels")
#  Creating a  list of numeric (non-binary) columns
numeric_columns = penguins_df.select_dtypes(include=["number"]).nunique()
numeric_columns = numeric_columns[numeric_columns > 2].index.tolist()  

# Adding cluster labels to the DataFrame
penguins_df["label"] = Kn.labels_

# Aggregating numeric data by cluster (label)
stat_penguins = penguins_df.groupby("label")[numeric_columns].mean()

stat_penguins