Gower Distance for Mixed-Type Features

Quick Overview

Implement Gower distance in NumPy for rows that mix continuous, ordinal and nominal features with missing values. It tests per-feature dissimilarities, masking missing values out of a weighted average, range normalization from a reference set, input validation, and vectorized pairwise computation.

Gower Distance for Mixed-Type Features

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `gower_distances(X, feature_types, Y=None, weights=None)` returning the `(n, m)` Gower distance matrix between rows of `X` and rows of `Y` (`Y` defaults to `X`). Missing values are `NaN`. The distance between two rows is $$D = \frac{\sum_j w_j \delta_j s_j}{\sum_j w_j \delta_j}$$ where $\delta_j = 1$ only if feature j is observed in both rows (0 otherwise) and $s_j$ is the per-feature term: - `continuous` and `ordinal` (treated identically): $s_j = \min(|a - b| / r_j, 1)$, with $r_j$ = max - min of column j over the observed values of `X` only. - If $r_j = 0$, then $s_j = 0$, but the feature still counts in the denominator. - `nominal`: 0 if equal, else 1. - If no feature is observed in both rows, or the total weight is zero, the distance is `NaN`. Example: ```python X = [[1.0, 2.0, 0.0], [3.0, 1.0, 1.0], [np.nan, 3.0, 0.0]] gower_distances(X, ["continuous", "ordinal", "nominal"]) # [[0.0, 0.8333, 0.25], # [0.8333, 0.0, 1.0 ], # [0.25, 1.0, 0.0 ]] # D[0,1] = (1 + 0.5 + 1) / 3, D[0,2] = (0.5 + 0) / 2 ``` ```hint Missing values Keep the numerator and the denominator as two separate `(n, m)` accumulators, and decide what a missing value should do to each of them. ``` ```hint Constant columns A column with a single observed value has range zero. Make sure you never divide by it, and check what the rules say it adds to the denominator. ``` ### Constraints & Assumptions - `feature_types` entries are case-insensitive, one per column. - Raise `ValueError` if `X` is not 2-D, `Y` is not 2-D or has a different column count, `feature_types` has the wrong length or an unknown type, or `weights` is not shape `(d,)` and non-negative. - `weights` defaults to all ones. Nominal codes are numeric floats. ### What a Strong Answer Covers - The per-feature term for each type, including the zero-range rule and the clip at 1. - Missing values removed from both the numerator and the denominator, with `NaN` when a pair shares no observed feature or has zero total weight. - Ranges taken from the observed values of `X` only, and why that matters when `Y` is a separate query set. - Validation for every listed `ValueError` case, with case-insensitive type names. - A vectorized implementation and its time and memory cost. ### Follow-up Questions - How would you treat ordinal features more faithfully than as continuous values? - How would you scale this to ${10^6}$ training rows for KNN queries? - Why compute ranges from `X` only, and what breaks if queries fall outside them?

Overview: Implement Gower distance in NumPy for rows that mix continuous, ordinal and nominal features with missing values. It tests per-feature dissimilarities, masking missing values out of a weighted average, range normalization from a reference set, input validation, and vectorized pairwise computation.

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

Implement gower_distances(X, feature_types, Y=None, weights=None) returning the (n, m) Gower distance matrix between rows of X and rows of Y (Y defaults to X). Missing values are NaN. The distance between two rows is

D=∑jwjδjsj∑jwjδjD = \frac{\sum_j w_j \delta_j s_j}{\sum_j w_j \delta_j}

where δj=1\delta_j = 1 only if feature j is observed in both rows (0 otherwise) and sjs_j is the per-feature term:

  • continuous and ordinal (treated identically): sj=min⁡(∣a−b∣/rj,1)s_j = \min(|a - b| / r_j, 1) , with rjr_j = max - min of column j over the observed values of X only.
  • If rj=0r_j = 0 , then sj=0s_j = 0 , but the feature still counts in the denominator.
  • nominal : 0 if equal, else 1.
  • If no feature is observed in both rows, or the total weight is zero, the distance is NaN .

Example:

X = [[1.0,    2.0, 0.0],
     [3.0,    1.0, 1.0],
     [np.nan, 3.0, 0.0]]
gower_distances(X, ["continuous", "ordinal", "nominal"])
# [[0.0,    0.8333, 0.25],
#  [0.8333, 0.0,    1.0 ],
#  [0.25,   1.0,    0.0 ]]
# D[0,1] = (1 + 0.5 + 1) / 3,  D[0,2] = (0.5 + 0) / 2

Constraints & Assumptions

  • feature_types entries are case-insensitive, one per column.
  • Raise ValueError if X is not 2-D, Y is not 2-D or has a different column count, feature_types has the wrong length or an unknown type, or weights is not shape (d,) and non-negative.
  • weights defaults to all ones. Nominal codes are numeric floats.

What a Strong Answer Covers Guidance

  • The per-feature term for each type, including the zero-range rule and the clip at 1.
  • Missing values removed from both the numerator and the denominator, with NaN when a pair shares no observed feature or has zero total weight.
  • Ranges taken from the observed values of X only, and why that matters when Y is a separate query set.
  • Validation for every listed ValueError case, with case-insensitive type names.
  • A vectorized implementation and its time and memory cost.

Follow-up Questions Guidance

  • How would you treat ordinal features more faithfully than as continuous values?
  • How would you scale this to 106{10^6} training rows for KNN queries?
  • Why compute ranges from X only, and what breaks if queries fall outside them?