SMOTE Oversampling From Scratch in NumPy

Quick Overview

Implement SMOTE in NumPy by building a nearest-neighbour table over the minority rows and interpolating synthetic samples between each row and a chosen neighbour. It tests vectorized distance computation, deterministic tie-breaking, seeded random sampling and input validation for class-imbalance preprocessing.

SMOTE Oversampling From Scratch in NumPy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement SMOTE oversampling with NumPy as two functions. `minority_neighbors(X_min, k)` returns an `(n_min, k)` integer table that lists, for each row, its k nearest other rows. Use Euclidean distance, exclude the row itself, order neighbours by ascending distance, and break ties by the lowest index. `smote(X, y, n_synthetic, k=5, seed=0)` returns `(X_res, y_res)`: the original rows unchanged, followed by `n_synthetic` rows of the form `x_i + gap * (x_nn - x_i)` labelled with the minority class. Example: ```python minority_neighbors(np.array([[0.], [1.], [2.], [4.]]), 2) # -> [[1, 2], [0, 2], [1, 0], [2, 1]] ``` For `smote`, create `rng = np.random.default_rng(seed)` and make these draws for each synthetic sample, in this order: ```python i = rng.integers(n_min) # base minority row j = rng.integers(k) # column of neighbour table gap = rng.random() # in [0, 1) new = X_min[i] + gap * (X_min[nn[i, j]] - X_min[i]) ``` ```hint Building the table Broadcasting gives every pairwise distance in one array. Decide how to keep each row out of its own neighbour list before you sort. ``` ```hint Tie order Row 1 in the example is equally close to rows 0 and 2. Check which kind of sort keeps equal values in index order. ``` ### Constraints & Assumptions - The minority class is the label with the fewest rows, and a count tie goes to the lowest label. `X_min` keeps the original row order. - Raise `ValueError` when `k` is outside `[1, n_min - 1]`, `n_synthetic` is negative, `X` is not 2-D, `y` is not 1-D, or `X` and `y` have different row counts. - `X_res` is float and `y_res` keeps `y.dtype`. With `n_synthetic = 0`, the function returns the inputs unchanged. ### What a Strong Answer Covers - Builds the neighbour table over minority rows only, with the row itself excluded and distance ties broken by lowest index. - Selects the minority class with the stated tie rule and keeps `X_min` in original row order. - Makes the three random draws per sample in the specified order from one seeded generator and interpolates toward the chosen neighbour. - Validates every listed input condition, returns the expected dtypes and handles the zero-sample case. - States the time and memory cost of the pairwise distance computation. ### Follow-up Questions - How does Borderline-SMOTE change which minority points get oversampled? - How would you scale the neighbour search beyond the $O(n^2)$ distance matrix? - Why must SMOTE be applied only inside training folds?

Overview: Implement SMOTE in NumPy by building a nearest-neighbour table over the minority rows and interpolating synthetic samples between each row and a chosen neighbour. It tests vectorized distance computation, deterministic tie-breaking, seeded random sampling and input validation for class-imbalance preprocessing.

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

Implement SMOTE oversampling with NumPy as two functions.

minority_neighbors(X_min, k) returns an (n_min, k) integer table that lists, for each row, its k nearest other rows. Use Euclidean distance, exclude the row itself, order neighbours by ascending distance, and break ties by the lowest index.

smote(X, y, n_synthetic, k=5, seed=0) returns (X_res, y_res): the original rows unchanged, followed by n_synthetic rows of the form x_i + gap * (x_nn - x_i) labelled with the minority class.

Example:

minority_neighbors(np.array([[0.], [1.], [2.], [4.]]), 2)
# -> [[1, 2], [0, 2], [1, 0], [2, 1]]

For smote, create rng = np.random.default_rng(seed) and make these draws for each synthetic sample, in this order:

i   = rng.integers(n_min)   # base minority row
j   = rng.integers(k)       # column of neighbour table
gap = rng.random()          # in [0, 1)
new = X_min[i] + gap * (X_min[nn[i, j]] - X_min[i])

Constraints & Assumptions

  • The minority class is the label with the fewest rows, and a count tie goes to the lowest label. X_min keeps the original row order.
  • Raise ValueError when k is outside [1, n_min - 1] , n_synthetic is negative, X is not 2-D, y is not 1-D, or X and y have different row counts.
  • X_res is float and y_res keeps y.dtype . With n_synthetic = 0 , the function returns the inputs unchanged.

What a Strong Answer Covers Guidance

  • Builds the neighbour table over minority rows only, with the row itself excluded and distance ties broken by lowest index.
  • Selects the minority class with the stated tie rule and keeps X_min in original row order.
  • Makes the three random draws per sample in the specified order from one seeded generator and interpolates toward the chosen neighbour.
  • Validates every listed input condition, returns the expected dtypes and handles the zero-sample case.
  • States the time and memory cost of the pairwise distance computation.

Follow-up Questions Guidance

  • How does Borderline-SMOTE change which minority points get oversampled?
  • How would you scale the neighbour search beyond the O(n2)O(n^2) distance matrix?
  • Why must SMOTE be applied only inside training folds?