Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Clustering and Discovery lessons
Hierarchical discovery · ML-U-K1 · 25–35 MIN

Discovery checkpoint

  1. Retrieval 1Retrieve and applyCurrent exercise

Outputs you create

evidence
  1. Dataframe with k, inertia and silhouette columns for k=2–8.
sizes
  1. Group sizes indexed by cluster label.
profiles
  1. Original-unit means grouped by aligned cluster labels.
labels
  1. One cluster label per fitted row; equivalent consistent label names are accepted.
CLUSTER36B · first 8 rows
length_mmwidth_cm
1085.4812.3736
795.0656.81964
302.85713.4007
1005.8310.7201
725.74214.2927
1330.129.57362
805.4488.75158
720.48110.093
Your task
  1. Scale every CLUSTER36B observation
  2. Compare k=2 through 8 with inertia and silhouette
  3. Choose a defensible fitted grouping, and store evidence, labels, sizes and original-unit profiles.
  4. Draw length against width with distinct group markers and labelled axes, then qualify the interpretation.
evidencesizesprofileslabels
Hints

Think: Reconstruct discovery without importing a supervised target or a unique correct grouping.

Tools: Scaling, KMeans k comparison, silhouette, sizes and original-unit profiles.

Approach: Define the population, compare resolutions, choose a defensible grouping and report its profiles with a qualified visual.

Explained solution
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
import seaborn as sns
X=df.copy()
scaler=StandardScaler()
scaled=scaler.fit_transform(X)
rows=[]
for k in range(2,min(8,len(X)-1)+1):
    candidate=KMeans(n_clusters=k,n_init=20,random_state=42).fit(scaled)
    score=silhouette_score(scaled,candidate.labels_,sample_size=min(2000,len(X)),random_state=42)
    rows.append({'k':k,'inertia':candidate.inertia_,'silhouette':score})
evidence=pd.DataFrame(rows)
# Three is an illustrative choice to discuss against the evidence, not a unique optimum.
model=KMeans(n_clusters=3,n_init=20,random_state=42).fit(scaled)
labels=model.labels_
sizes=pd.Series(labels).value_counts().sort_index()
profiles=X.groupby(labels).mean()
fig,ax=plt.subplots(figsize=(6,4))
sns.scatterplot(data=X,x='length_mm',y='width_cm',hue=labels,style=labels,ax=ax)
ax.set(xlabel='Length (mm)',ylabel='Width (cm)',title='Exploratory measurement groups')
ax.legend()
fig.savefig('clusters.png',dpi=150,bbox_inches='tight')
print(evidence)

The workflow joins geometric evidence with substantive interpretation; neither the selected k nor the group IDs claim a hidden class truth.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.