Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Clustering and Discovery lessons
K-Means · ML-U05 · 12–18 MIN

Describe clusters in meaningful units

Use sizes and original-unit profiles with named features.

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

Understand the idea

Cluster labels may be permuted without changing the grouping. Report original-unit feature summaries and population sizes so the result is interpretable.

Use sizes and original-unit profiles with named features.GroupSizeMean length (mm)0n₀μ₀1n₁μ₁2n₂μ₂Aggregate original measurements with aligned assignments.
Use sizes and original-unit profiles with named features.Scroll the diagram horizontally if needed.

What the syntax does

X.groupby(labels)
  • Groups original-unit rows by their aligned fitted assignments.
pd.Series(labels).value_counts()
  • Counts how many fitted observations belong to each named group.

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[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]
scaled
Standardised features in the same row/column order as X.
scaled = StandardScaler().fit_transform(X)
labels
One cluster label per fitted row; equivalent consistent label names are accepted.
labels = KMeans(n_clusters=3, n_init=20, random_state=42).fit_predict(scaled)

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
sizes
  1. Group sizes indexed by cluster label.
penguins · first 8 rows
islandbill_length_mmbill_depth_mmflipper_length_mmbody_mass_gsexyear
Torgersen39.118.71813750male2007
Torgersen39.517.41863800female2007
Torgersen40.3181953250female2007
Torgersen36.719.31933450female2007
Torgersen39.320.61903650male2007
Torgersen38.917.81813625female2007
Torgersen39.219.61954675male2007
Torgersen41.117.61823200female2007
Your task
  1. Report cluster sizes and original-unit means.
answersizes
Hints

Think: Assignments must align with the original rows whose profiles you report.

Tools: groupby.mean and value_counts.

Approach: Use the supplied labels to aggregate original measurements and count group membership.

Explained solution
answer=X.groupby(labels).mean()
sizes=pd.Series(labels).value_counts().sort_index()

Original-unit means explain group characteristics while sizes reveal whether a profile describes many rows or a tiny subset.

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.