K-Means on Raw vs Standardized Features

Quick Overview

Implement z-score standardization, Lloyd's k-means with fixed seed rows, and the adjusted Rand index, then compare the clusterings found on raw and standardized features. It tests how feature scale drives Euclidean distance, careful handling of ties, empty clusters and stopping rules, and how to compare two labelings whose cluster ids are arbitrary.

K-Means on Raw vs Standardized Features

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `standardize`, `kmeans` (Lloyd's algorithm), `adjusted_rand_index`, and `compare_raw_vs_standardized(X, init_idx, max_iter=100, tol=1e-8)` in Python with NumPy. The comparison runs k-means on raw `X` and on standardized `Z`, seeding each run with its own rows `init_idx`, and returns a dict with keys `labels_raw`, `labels_std`, `inertia_raw`, `inertia_std` and `ari` (the ARI between the two labelings). The functions follow these rules: - `standardize`: column z-score with population std (`ddof=0`). Constant columns become 0. - `kmeans(X, init_centroids, max_iter, tol)` returns `(labels, centroids, inertia)`. Distance ties go to the lowest centroid index, and an empty cluster keeps its previous centroid. - Stop when the largest centroid shift (Euclidean) is `<= tol` or after `max_iter` updates. Final labels and inertia (sum of squared distances) are computed against the final centroids. - `adjusted_rand_index`: Hubert-Arabie ARI (matches `sklearn`, label-permutation invariant). Return `1.0` when the denominator is 0. Example: ```python X = [[0, 100*j] for j in range(10)] + [[1, 100*j] for j in range(10)] out = compare_raw_vs_standardized(X, [4, 15]) out["labels_raw"] # ([0]*5 + [1]*5) * 2 out["labels_std"] # [0]*10 + [1]*10 out["inertia_raw"] # 400005.0 out["inertia_std"] # 20.0 out["ari"] # -1/18 ``` ```hint Which column decides the distance Before coding, compare the spread of the two columns in the example. Which one controls Euclidean distance on the raw data, and which one after z-scoring? ``` ```hint Two places to slip Labels computed inside the loop belong to the centroids from before the last update. For ARI, every term is a sum of "n choose 2" over the cells, the row sums or the column sums of one contingency table. ``` ### Constraints & Assumptions - `X` is a finite 2-D float array of shape `(n, d)` with `n >= 2`. - `init_idx` holds k distinct valid row indices. - Labels are `int` arrays of length n, and inertias are floats. ### What a Strong Answer Covers - Standardization with the population std, including constant columns, without producing NaN. - A Lloyd loop that follows the stated tie, empty-cluster, stopping and final-assignment rules. - ARI built from a contingency table, invariant to label permutation, with the zero-denominator case handled. - Why the raw and standardized runs split the example differently, and why their ARI is negative. - The time and memory cost of the distance step and of the ARI computation. ### Follow-up Questions - When can standardizing make the clustering worse? - Why can ARI be negative, as in the example? - Without a given `init_idx`, how would you seed the runs, and how would you check that the raw vs standardized difference is larger than the variation between seeds?

Overview: Implement z-score standardization, Lloyd's k-means with fixed seed rows, and the adjusted Rand index, then compare the clusterings found on raw and standardized features. It tests how feature scale drives Euclidean distance, careful handling of ties, empty clusters and stopping rules, and how to compare two labelings whose cluster ids are arbitrary.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement standardize, kmeans (Lloyd's algorithm), adjusted_rand_index, and compare_raw_vs_standardized(X, init_idx, max_iter=100, tol=1e-8) in Python with NumPy. The comparison runs k-means on raw X and on standardized Z, seeding each run with its own rows init_idx, and returns a dict with keys labels_raw, labels_std, inertia_raw, inertia_std and ari (the ARI between the two labelings).

The functions follow these rules:

  • standardize : column z-score with population std ( ddof=0 ). Constant columns become 0.
  • kmeans(X, init_centroids, max_iter, tol) returns (labels, centroids, inertia) . Distance ties go to the lowest centroid index, and an empty cluster keeps its previous centroid.
  • Stop when the largest centroid shift (Euclidean) is <= tol or after max_iter updates. Final labels and inertia (sum of squared distances) are computed against the final centroids.
  • adjusted_rand_index : Hubert-Arabie ARI (matches sklearn , label-permutation invariant). Return 1.0 when the denominator is 0.

Example:

X = [[0, 100*j] for j in range(10)] + [[1, 100*j] for j in range(10)]
out = compare_raw_vs_standardized(X, [4, 15])
out["labels_raw"]   # ([0]*5 + [1]*5) * 2
out["labels_std"]   # [0]*10 + [1]*10
out["inertia_raw"]  # 400005.0
out["inertia_std"]  # 20.0
out["ari"]          # -1/18

Constraints & Assumptions

  • X is a finite 2-D float array of shape (n, d) with n >= 2 .
  • init_idx holds k distinct valid row indices.
  • Labels are int arrays of length n, and inertias are floats.

What a Strong Answer Covers Guidance

  • Standardization with the population std, including constant columns, without producing NaN.
  • A Lloyd loop that follows the stated tie, empty-cluster, stopping and final-assignment rules.
  • ARI built from a contingency table, invariant to label permutation, with the zero-denominator case handled.
  • Why the raw and standardized runs split the example differently, and why their ARI is negative.
  • The time and memory cost of the distance step and of the ARI computation.

Follow-up Questions Guidance

  • When can standardizing make the clustering worse?
  • Why can ARI be negative, as in the example?
  • Without a given init_idx , how would you seed the runs, and how would you check that the raw vs standardized difference is larger than the variation between seeds?