SMOTE-NC Distance and Sample Generation
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement SMOTE-NC for a binary dataset with mixed continuous and categorical features. `categorical_mask` is a boolean array marking the categorical columns. Write three functions:
- `smotenc_penalty(X_min, categorical_mask)` returns the median of the population std (`ddof=0`) of the continuous columns of `X_min`. It returns `1.0` when there are no continuous columns.
- `smotenc_distances(A, B, categorical_mask, penalty)` returns a `(len(A), len(B))` matrix of distances, where $m(a, b)$ is the number of categorical columns in which the two rows differ:
$$d(a, b) = \sqrt{\sum_{c \in \text{cont}} (a_c - b_c)^2 + \text{penalty}^2 \cdot m(a, b)}$$
- `smotenc_fit_resample(X, y, categorical_mask, ratio=1.0, k=5, seed=0)` returns `(X_res, y_res)` with synthetic minority rows appended.
The resampling follows these rules:
- The minority is the less frequent label. When the two counts tie, the lower label is the minority.
- Raise `ValueError` unless there are exactly 2 classes and `1 <= k < n_min`.
- Generate `max(0, floor(ratio * n_maj) - n_min)` rows. If that is 0, return copies of the inputs.
- A row's neighbours are the `k` nearest other minority rows, ranked by a stable sort, so ties go to the lower index. Minority rows are indexed in the order they appear in `X`.
- Each categorical value of a synthetic row is the per-column mode over the base row's `k` neighbours, with ties going to the smallest value.
- Create `rng = np.random.default_rng(seed)`. For each sample, draw `i = rng.integers(n_min)`, then `j = rng.integers(k)`, then `gap = rng.random()`. The base is minority row `i` and `nb` is its `j`-th neighbour. Set the continuous features to `base + gap * (nb - base)`.
- Output the original rows followed by the synthetic rows, which carry the minority label.
Example:
```python
mask = [False, False, True]
smotenc_distances([[0, 0, 1]], [[3, 4, 2], [0, 0, 1]], mask, penalty=2.0)
# [[sqrt(25 + 4), 0.0]] -> [[5.385..., 0.0]]
```
Against the first row of `B`, the continuous columns differ by 3 and 4 (9 + 16 = 25) and the one categorical column differs, which adds `2.0 ** 2 = 4`. The second row of `B` is identical to the query, so its distance is 0.
```hint Pairwise distances
Broadcasting `A` to shape `(len(A), 1, d)` and `B` to `(1, len(B), d)` gives every pair at once. Use the mask to split the last axis into squared differences and mismatch counts.
```
```hint Neighbour lists
Every row is at distance 0 from itself. Find a way to keep a row out of its own neighbour list that does not disturb the stable tie order among the other rows.
```
### Constraints & Assumptions
- `X` is a 2-D numeric array of shape `(n, d)`. Categorical columns are numerically encoded and arrive as floats in `X`.
- `categorical_mask` has length `d`.
- `y` must hold exactly two distinct labels.
- `k` must satisfy `1 <= k < n_min`, where `n_min` is the minority count.
- The target minority count is `floor(ratio * n_maj)`.
### What a Strong Answer Covers
- A vectorized distance that adds `penalty ** 2` per categorical mismatch, with the penalty computed from the population std of the minority's continuous columns.
- Minority selection with the lower-label tie rule, the input validation, and the early return when no rows are needed.
- Neighbour lists that exclude the row itself and break distance ties by lower index.
- Interpolation on continuous columns only, with categorical columns set to the neighbour mode and the smallest value winning ties.
- RNG draws in the specified order, the required output order, and the time and memory cost of the `n_min` by `n_min` distance matrix.
### Follow-up Questions
- Why scale the mismatch cost by the median continuous std?
- How would this scale to a minority class with 100,000 rows?
- What breaks if every feature is categorical?
Overview: Implement SMOTE-NC oversampling for a binary dataset with mixed continuous and categorical features: the median-std mismatch penalty, the mixed-type distance matrix and seeded synthetic row generation. It tests NumPy broadcasting, neighbour tie-breaking and how categorical columns are handled when rebalancing classes.