K-Modes Clustering for Categorical Data

Quick Overview

Implement k-modes clustering in NumPy, with a vectorized matching dissimilarity and a fit loop that follows fixed tie rules, keeps empty clusters' modes and checks for convergence. It tests how Lloyd-style clustering carries over to categorical features, plus careful dtype and edge-case handling.

K-Modes Clustering for Categorical Data

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `matching_dissimilarity(X, modes)`, which returns an `int64` matrix of shape `(n_samples, n_modes)` counting mismatched attributes. Also implement `fit_kmodes(X, init_modes, max_iter=100)`, which runs k-modes from the given initial modes and returns `(labels, modes, cost, n_iter)`. The functions must follow these rules: - Each iteration assigns every row to its nearest mode (ties go to the lowest mode index), then sets each attribute of a mode to its cluster's most frequent value (ties go to the smallest value). An empty cluster keeps its previous mode. - Stop when labels match the previous iteration's labels (modes are still updated that iteration) or after `max_iter` iterations. `n_iter` is the number of iterations run. - `cost` is a Python `int`: the summed dissimilarity of each row to its final mode, using the final labels. `labels` are `int64`. - Raise `ValueError` for non-2-D inputs or a column-count mismatch, and for `max_iter < 1`. - Categories may be integers or strings. Example: ```python X = [[0,0,0],[0,0,1],[0,1,0],[2,2,2],[2,2,1],[1,2,2]] init_modes = [[0,0,1],[1,2,2]] fit_kmodes(X, init_modes) # labels=[0,0,0,1,1,1], modes=[[0,0,0],[2,2,2]], cost=4, n_iter=3 fit_kmodes(X, init_modes, max_iter=1) # labels=[0,0,0,1,0,1], modes=[[0,0,0],[1,2,2]], cost=6, n_iter=1 ``` ```hint Comparing all pairs at once Every row against every mode is one elementwise comparison once each array gets an extra axis. Decide which axis the mismatches are summed over. ``` ```hint Tie rules and dtypes Check the order in which `np.unique` returns values and which index `np.argmin` and `np.argmax` return on a tie. Then check what happens when a long string category is written into a modes array created from shorter strings. ``` ### Constraints & Assumptions - Only NumPy is available. - `init_modes` is given, so initialization strategies such as Huang's or Cao's are out of scope. ### What a Strong Answer Covers - A vectorized `matching_dissimilarity` that validates shapes and returns `int64`. - An assign-then-update loop that applies both tie rules and keeps an empty cluster's previous mode. - The stopping rule, with `n_iter` counting the iteration that confirms the labels did not change. - A cost computed against the final modes with the final labels and returned as a Python `int`. - Support for string categories without truncation, and an argument for why the cost never increases. ### Follow-up Questions - How would you choose initial modes without them being supplied? - How would you extend this to mixed numeric and categorical features? - Why can't the cost increase, and how does this scale to large `n`?

Overview: Implement k-modes clustering in NumPy, with a vectorized matching dissimilarity and a fit loop that follows fixed tie rules, keeps empty clusters' modes and checks for convergence. It tests how Lloyd-style clustering carries over to categorical features, plus careful dtype and edge-case handling.

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

Implement matching_dissimilarity(X, modes), which returns an int64 matrix of shape (n_samples, n_modes) counting mismatched attributes. Also implement fit_kmodes(X, init_modes, max_iter=100), which runs k-modes from the given initial modes and returns (labels, modes, cost, n_iter).

The functions must follow these rules:

  • Each iteration assigns every row to its nearest mode (ties go to the lowest mode index), then sets each attribute of a mode to its cluster's most frequent value (ties go to the smallest value). An empty cluster keeps its previous mode.
  • Stop when labels match the previous iteration's labels (modes are still updated that iteration) or after max_iter iterations. n_iter is the number of iterations run.
  • cost is a Python int : the summed dissimilarity of each row to its final mode, using the final labels. labels are int64 .
  • Raise ValueError for non-2-D inputs or a column-count mismatch, and for max_iter < 1 .
  • Categories may be integers or strings.

Example:

X = [[0,0,0],[0,0,1],[0,1,0],[2,2,2],[2,2,1],[1,2,2]]
init_modes = [[0,0,1],[1,2,2]]
fit_kmodes(X, init_modes)
# labels=[0,0,0,1,1,1], modes=[[0,0,0],[2,2,2]], cost=4, n_iter=3
fit_kmodes(X, init_modes, max_iter=1)
# labels=[0,0,0,1,0,1], modes=[[0,0,0],[1,2,2]], cost=6, n_iter=1

Constraints & Assumptions

  • Only NumPy is available.
  • init_modes is given, so initialization strategies such as Huang's or Cao's are out of scope.

What a Strong Answer Covers Guidance

  • A vectorized matching_dissimilarity that validates shapes and returns int64 .
  • An assign-then-update loop that applies both tie rules and keeps an empty cluster's previous mode.
  • The stopping rule, with n_iter counting the iteration that confirms the labels did not change.
  • A cost computed against the final modes with the final labels and returned as a Python int .
  • Support for string categories without truncation, and an argument for why the cost never increases.

Follow-up Questions Guidance

  • How would you choose initial modes without them being supplied?
  • How would you extend this to mixed numeric and categorical features?
  • Why can't the cost increase, and how does this scale to large n ?