Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Clustering and Discovery lessons
K-Means · ML-U04 · 18–25 MIN

Choosing k requires evidence and judgement

Combine compactness, separation and useful interpretation.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeAdapt the Python
  3. PractiseAdapt the Python
  4. TransferCompute and inspect the evidence

Understand the idea

Inertia decreases as more centres are added, so its minimum alone does not select k. Silhouette describes separation relative to cohesion. Neither proves a single natural grouping.

Combine compactness, separation and useful interpretation.Candidate k valuesInertia + silhouetteSizes + profiles + purposeA score supports a choice; it does not prove natural classes.
Combine compactness, separation and useful interpretation.Scroll the diagram horizontally if needed.

What the syntax does

model.inertia_
  • Reads the fitted sum of squared distances to assigned centroids; it tends to decrease as k grows.

Supplied for this practice

These objects are prepared afresh before your editor runs.

X
Feature dataframe for the declared population, preserving row indices.
X = df.copy()
scaler
Already fitted coordinate system learned from X; transform reuses its statistics without fitting again. Fitted on X; reuse without refitting.
scaled
Standardised features in the same row/column order as X.
scaled = scaler.fit_transform(X)

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
CLUSTER36 · first 8 rows
length_mmwidth_cm
1106.656.36006
1262.6613.292
317.1385.44237
1044.748.89315
994.127.01435
1307.7912.7223
1023.1113.9453
1163.636.99248
Your task
  1. Fit k=3 and report inertia.
answer
Hints

Think: Inertia is a within-cluster squared-distance objective.

Tools: The fitted KMeans.inertia_ attribute.

Approach: Fit the declared k on the supplied scaled population and read its objective value.

Explained solution
model=KMeans(n_clusters=3,n_init=20,random_state=42).fit(scaled)
answer=model.inertia_

The value summarises compactness for this representation and population; it is not supervised accuracy.

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.