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
from sklearn.pipeline import make_pipeline

# Loading and examining the dataset
penguins_df = pd.read_csv("penguins.csv")
penguins_df.head()

Cluster analysis

from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
import pandas as pd

varieties=['chinstrap','chinstrap','adelie','gentoo','gentoo']

# Sample DataFrame for demonstration
data = {
    'bill_length_mm': [39.1, 39.5, 40.3, 36.7, 39.3],
    'bill_depth_mm': [18.7, 17.4, 18.0, 19.3, 20.6],
    'flipper_length_mm': [181, 186, 195, 193, 190],
    'body_mass_g': [3750, 3800, 3250, 3450, 3650],
    'sex': ['male', 'female', 'female', 'male', 'female']
}
penguins_df = pd.DataFrame(data)

# pipe standard scaler and Kmens and apply to penguins to cluster then into 3 groups
scaler = StandardScaler()
stat_penguins = penguins_df.drop(columns=['sex'])

#set kmeans for 3 clusters
kmeans = KMeans(n_clusters=3)

#set pipeline
pipeline = make_pipeline(scaler, kmeans)

#generate model
pipeline.fit(stat_penguins)
preds= pipeline.predict(stat_penguins)
print(preds)

#cross tabulate varietie with the predicted 3 groups
df = pd.DataFrame({'preds': preds, 'varieties': varieties})
ct = pd.crosstab(df['preds'],df['varieties'])
print(ct)