Vectorized Gower Distance with K-Medoids Clustering

Quick Overview

Implement a vectorized Gower distance for a DataFrame with numeric and categorical columns, then use the matrix for k-medoids and agglomerative clustering. It tests NumPy broadcasting, exact tie-breaking rules, input validation, and knowing which linkages work with a non-Euclidean distance.

Vectorized Gower Distance with K-Medoids Clustering

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `gower_distance`, which returns the `(n, n)` Gower distance matrix of a mixed-type DataFrame without per-pair Python loops. Then use it in `k_medoids` and `cluster_mixed`. ```python def gower_distance(df, categorical=None, weights=None): ... def k_medoids(D, init_medoids, max_iter=100): ... def cluster_mixed(df, n_clusters, categorical=None, weights=None, linkage="average"): ... ``` `gower_distance` follows these rules: - When `categorical` is a list, exactly the listed columns are categorical and the rest are numeric. When it is `None`, a column is categorical if its dtype is non-numeric or bool. - A categorical feature contributes 0 when two values match and 1 when they differ. A numeric feature contributes `|x_i - x_j| / range`, where range is the column's max minus its min. A zero-range column contributes 0. - The result is the weighted mean over all columns. `weights` is a dict from column name to weight, and any column it does not name gets weight 1. Zero-range columns still count in the denominator. - A negative weight, or a total weight of zero, raises `ValueError`. - The matrix is symmetric with a zero diagonal. `k_medoids` works on a precomputed distance matrix `D` with initial medoid row indices `init_medoids`: - Assign each point to its nearest medoid. A tie goes to the lowest position in the medoid list. - Move each medoid to the member of its cluster with the smallest summed distance to the cluster's members. A tie goes to the lowest row index, and an empty cluster keeps its medoid. - Stop when the medoids do not change or after `max_iter` updates. With `max_iter=0` the function only assigns. - Return `(medoids, labels, cost)`. Each label is a position in `medoids`, and `cost` is the total distance from each point to its assigned medoid. `cluster_mixed` runs scikit-learn's `AgglomerativeClustering` on the precomputed Gower matrix. `linkage` must be `"single"`, `"complete"` or `"average"`, and anything else raises `ValueError`. The returned labels are renumbered `0, 1, ...` in order of first appearance. ```python df = pd.DataFrame({"age": [20.0, 30.0, 40.0], "city": ["a", "b", "a"], "income": [1.0, 1.0, 1.0]}) gower_distance(df) # [[0. , 0.5, 0.3333], # [0.5 , 0. , 0.5 ], # [0.3333, 0.5, 0. ]] gower_distance(df, weights={"age": 1, "city": 3, "income": 0})[0, 1] # 0.875 ``` For rows 0 and 1, age contributes `10 / 20 = 0.5`, city contributes 1, and the zero-range income column contributes 0 but still counts, so the mean is `1.5 / 3 = 0.5`. With weights 1, 3 and 0 the same pair gives `(0.5 + 3) / 4 = 0.875`. ```hint Broadcasting per column Each column's contribution is one `(n, n)` array built by comparing the column vector with itself on a new axis. Looping over columns is allowed. The loop to avoid is the one over pairs. ``` ```hint Tie rules for free `np.argmin` returns the first minimum. If each cluster's members are kept in ascending row order, both k-medoids tie rules follow from that. ``` ### Constraints & Assumptions - `gower_distance` may loop over columns but not over pairs of rows. - `numpy`, `pandas` and scikit-learn's `AgglomerativeClustering` are available. - `D` passed to `k_medoids` is a square, symmetric distance matrix, and `init_medoids` holds valid row indices. ### What a Strong Answer Covers - Column typing that follows the `categorical` rule, including bool columns under inference. - Broadcast per-column distances with the zero-range case, a weighted mean that still counts zero-range columns, and the two `ValueError` checks. - A k-medoids loop that applies both tie rules, leaves empty clusters alone, honors `max_iter` (including 0) and reports the cost of the final assignment. - A `cluster_mixed` that validates `linkage`, passes the matrix as precomputed distances and relabels by first appearance. - The time and memory cost in terms of `n`, the number of features and the cluster sizes. ### Follow-up Questions - How would you handle missing values in the Gower distance? - Why is `ward` linkage excluded here? - Why does the k-medoids cost never increase, and what guarantees the loop ends? - How would you scale this when the `(n, n)` matrix no longer fits in memory?

Overview: Implement a vectorized Gower distance for a DataFrame with numeric and categorical columns, then use the matrix for k-medoids and agglomerative clustering. It tests NumPy broadcasting, exact tie-breaking rules, input validation, and knowing which linkages work with a non-Euclidean distance.

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

Implement gower_distance, which returns the (n, n) Gower distance matrix of a mixed-type DataFrame without per-pair Python loops. Then use it in k_medoids and cluster_mixed.

def gower_distance(df, categorical=None, weights=None): ...
def k_medoids(D, init_medoids, max_iter=100): ...
def cluster_mixed(df, n_clusters, categorical=None, weights=None, linkage="average"): ...

gower_distance follows these rules:

  • When categorical is a list, exactly the listed columns are categorical and the rest are numeric. When it is None , a column is categorical if its dtype is non-numeric or bool.
  • A categorical feature contributes 0 when two values match and 1 when they differ. A numeric feature contributes |x_i - x_j| / range , where range is the column's max minus its min. A zero-range column contributes 0.
  • The result is the weighted mean over all columns. weights is a dict from column name to weight, and any column it does not name gets weight 1. Zero-range columns still count in the denominator.
  • A negative weight, or a total weight of zero, raises ValueError .
  • The matrix is symmetric with a zero diagonal.

k_medoids works on a precomputed distance matrix D with initial medoid row indices init_medoids:

  • Assign each point to its nearest medoid. A tie goes to the lowest position in the medoid list.
  • Move each medoid to the member of its cluster with the smallest summed distance to the cluster's members. A tie goes to the lowest row index, and an empty cluster keeps its medoid.
  • Stop when the medoids do not change or after max_iter updates. With max_iter=0 the function only assigns.
  • Return (medoids, labels, cost) . Each label is a position in medoids , and cost is the total distance from each point to its assigned medoid.

cluster_mixed runs scikit-learn's AgglomerativeClustering on the precomputed Gower matrix. linkage must be "single", "complete" or "average", and anything else raises ValueError. The returned labels are renumbered 0, 1, ... in order of first appearance.

df = pd.DataFrame({"age": [20.0, 30.0, 40.0],
                   "city": ["a", "b", "a"],
                   "income": [1.0, 1.0, 1.0]})
gower_distance(df)
# [[0.    , 0.5, 0.3333],
#  [0.5   , 0. , 0.5   ],
#  [0.3333, 0.5, 0.    ]]
gower_distance(df, weights={"age": 1, "city": 3, "income": 0})[0, 1]  # 0.875

For rows 0 and 1, age contributes 10 / 20 = 0.5, city contributes 1, and the zero-range income column contributes 0 but still counts, so the mean is 1.5 / 3 = 0.5. With weights 1, 3 and 0 the same pair gives (0.5 + 3) / 4 = 0.875.

Constraints & Assumptions

  • gower_distance may loop over columns but not over pairs of rows.
  • numpy , pandas and scikit-learn's AgglomerativeClustering are available.
  • D passed to k_medoids is a square, symmetric distance matrix, and init_medoids holds valid row indices.

What a Strong Answer Covers Guidance

  • Column typing that follows the categorical rule, including bool columns under inference.
  • Broadcast per-column distances with the zero-range case, a weighted mean that still counts zero-range columns, and the two ValueError checks.
  • A k-medoids loop that applies both tie rules, leaves empty clusters alone, honors max_iter (including 0) and reports the cost of the final assignment.
  • A cluster_mixed that validates linkage , passes the matrix as precomputed distances and relabels by first appearance.
  • The time and memory cost in terms of n , the number of features and the cluster sizes.

Follow-up Questions Guidance

  • How would you handle missing values in the Gower distance?
  • Why is ward linkage excluded here?
  • Why does the k-medoids cost never increase, and what guarantees the loop ends?
  • How would you scale this when the (n, n) matrix no longer fits in memory?