Understand the idea
Reference labels may be inspected after fitting for interpretation, but must not secretly determine features, k or the hierarchy cut. Discovery describes a chosen population under chosen measurements and geometry.
What the syntax does
X.assign(cluster=labels)- Attaches the assignments to the same observations; order must stay aligned.
pd.crosstab(cluster_labels, reference_labels)- Counts observed group/reference combinations after fitting.
- This descriptive table must not be used retroactively to select features, k or a cut.
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[['length', 'width']] 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- The requested result, with the values, labels and row order described by this task.
length | width | label |
|---|---|---|
| 236.033 | -0.805568 | A |
| 581.297 | 0.728558 | A |
| -1511.27 | -1.00866 | A |
| 99.0248 | -0.24496 | A |
| -13.0141 | -0.660765 | A |
| 681.179 | 0.602475 | A |
| 51.1472 | 0.873157 | A |
| 362.131 | -0.665605 | A |
- After the supplied measurement-only fit, build
answeras a table of cluster-by-reference class counts. - Keep clusters on rows and the external labels A, B, C on columns.
- Explain why this post-fit table is not a supervised accuracy score.
answerHints
Think: Keep external labels out of fitting and inspect their association only afterwards.
Tools: Use pd.Series with the observation index, then pd.crosstab.
Approach: Pair each supplied assignment with its reference class on the same row and count the pairs.
Explained solution
cluster_labels = pd.Series(labels, index=X.index, name='cluster')
answer = pd.crosstab(cluster_labels, df['label']).reindex(columns=['A','B','C'], fill_value=0)
A contingency table may help interpret groups. Arbitrary cluster IDs have no fixed one-to-one class meaning, and post-fit association does not validate universal types or predictive accuracy.