Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Clustering and Discovery lessons
Hierarchical discovery · ML-U08 · 12–18 MIN

Turn a hierarchy into groups

Choose a cut using evidence and purpose.

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

Understand the idea

A cut assigns observations to groups at a chosen resolution. Several cuts can be informative. Combine the dendrogram with sizes, profiles and the exploratory question.

Illustrative data

Illustrative data
ColumnValues
length_mm10, 11, 12, 25, 26, 40, 41, 42
width_cm1, 1.3, 0.7, 6, 6.2, 2, 2.4, 1.7

Click the highlighted code to change the result.

scaled = ().(example[["length_mm", "width_cm"]])
linkage_matrix = linkage(scaled, method="ward")
labels = cut_tree(linkage_matrix, n_clusters=).ravel()
3 groups at Ward distance 1.949.Ward distance · standardised coordinates4.30w3w1w2w4w5w8w6w7g0g0g0g1g1g2g2g2

scaled geometry · 3 groups · cut distance 1.949.

What the syntax does

cut_tree(linkage_matrix, n_clusters=3).ravel()
  • Reads the chosen number of groups from the fitted hierarchy.
  • n_clusters: 2, 3, 4
  • n_clusters is a positive integer no larger than the number of observations. cut_tree returns a one-column array; ravel turns it into the one-dimensional label array used to group the original rows.

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)
linkage_matrix
Ward linkage matrix of scaled_sample.
linkage_matrix = linkage(scaled, method='ward')

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. Cut the fitted Ward hierarchy into three groups and store one group assignment per row in answer.
answer
Hints

Think: A cut converts one hierarchy into a requested resolution.

Tools: cut_tree and ravel.

Approach: Cut the supplied linkage at the declared group count and flatten the assignments.

Explained solution
answer=cut_tree(linkage_matrix,n_clusters=3).ravel()

The one-dimensional labels align to the hierarchy’s original row order and can support later profiles.

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.