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
| Column | Values |
|---|---|
length_mm | 10, 11, 12, 25, 26, 40, 41, 42 |
width_cm | 1, 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()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_clustersis a positive integer no larger than the number of observations.cut_treereturns 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 onX; 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- The requested result, with the values, labels and row order described by this task.
length_mm | width_cm |
|---|---|
| 1106.65 | 6.36006 |
| 1262.66 | 13.292 |
| 317.138 | 5.44237 |
| 1044.74 | 8.89315 |
| 994.12 | 7.01435 |
| 1307.79 | 12.7223 |
| 1023.11 | 13.9453 |
| 1163.63 | 6.99248 |
- Cut the fitted Ward hierarchy into three groups and store one group assignment per row in
answer.
answerHints
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.