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 pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler# Loading and examining the dataset
df = pd.read_csv("penguins.csv")
df.head()df.info()cols_to_scale = df.drop('sex', axis=1)
cols_to_scale.head()# scale data
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(cols_to_scale)
# convert back to dataframe
df_scaled = pd.DataFrame(data=scaled_data, columns=cols_to_scale.columns)
df_scaled.head()df_preprocessed = pd.concat([df_scaled, df['sex']], axis=1)
df_preprocessed.head()# update category to numerical dummies
df_preprocessed = pd.get_dummies(df_preprocessed, dtype='int')
df_preprocessed.head()inertias = []
for i in range(1, 11):
kmeans = KMeans(n_clusters=i, random_state=42).fit(df_preprocessed)
inertias.append(kmeans.inertia_)
plt.plot(range(1, 11), inertias, marker='o')
plt.xlabel('Number of clusters')
plt.ylabel('Inertias')
plt.show()
kmeans = KMeans(n_clusters=4, random_state=42).fit(df_preprocessed)
df_preprocessed['label'] = kmeans.labels_
df_preprocessed.head()plt.scatter(df_preprocessed['label'], df_preprocessed['culmen_length_mm'], c=kmeans.labels_, cmap='viridis')
plt.xlabel('Cluster')
plt.ylabel('culmen_length_mm')
plt.xticks(range(int(df_preprocessed['label'].min()), int(df_preprocessed['label'].max()) + 1))
plt.title('K-means Clustering (K=4)')
plt.show()df_preprocessed.head()df_num_cols = df_preprocessed.drop(['sex_FEMALE', 'sex_MALE'], axis=1)
stat_penguins = df_num_cols.groupby('label').mean()
stat_penguins