Rare Rows, Made in Between

Machine Learning in CodeMedium+20 XP+20

Rare Rows, Made in Between

In When One Class Is Rare, SMOTE gave the rare class more rows by interpolating between real ones: each new row is a plausible point placed between a real rare row and one of its rare neighbours, not a copy. Here you build that step yourself.

To make one new row, SMOTE:

  1. starts from a rare row aaa;
  2. lists the other rare rows by straight-line (Euclidean) distance from aaa, nearest first. Rows of the common class are never neighbours;
  3. picks one of them, ccc;
  4. picks a gap ggg between 0 and 1, and puts the new row at
a+g (c−a)a + g\,(c - a)a+g(c−a)

feature by feature. So g=0g = 0g=0 lands exactly on aaa, g=1g = 1g=1 lands exactly on ccc, and g=0.5g = 0.5g=0.5 lands halfway between them.

The library makes the choices in steps 3 and 4 at random. To make your output checkable, every new row here comes with its choices written down.

Task: write smote_rows(X, y, minority, recipes).

  • X is a list of rows, each a list of numbers, and y holds one label per row. minority is the rare class's label.
  • recipes is a list of (row, rank, gap) tuples, one per new row. row is the index in X of the starting rare row aaa. rank picks the neighbour ccc: 1 is the nearest other rare row, 2 the second nearest, and so on. gap is ggg.
  • If two rare rows are exactly the same distance from aaa, the one with the smaller index in X counts as nearer.
  • A row is never its own neighbour. A different rare row that happens to hold identical values is a genuine neighbour, at distance 0.

Return the new rows, one per recipe and in the same order, with every value rounded to 4 decimal places.

In every test, each recipe's row is a rare row, and its rank is never more than the number of other rare rows.

Examples

X = [[1.0, 1.0], [2.0, 1.5], [8.0, 7.0], [1.5, 3.0], [9.0, 6.0], [7.5, 8.0], [3.0, 2.0]]
y = [1, 1, 0, 1, 0, 0, 1]
minority = 1
recipes = [(0, 1, 0.5), (3, 2, 0.25)]
returns [[1.5, 1.25], [1.875, 2.75]]
X = [[10.0, 50.0], [12.0, 52.0], [11.0, 51.0], [20.0, 40.0], [15.0, 60.0]]
y = ['fraud', 'ok', 'ok', 'fraud', 'fraud']
minority = 'fraud'
recipes = [(0, 1, 0.4), (4, 2, 0.1)]
returns [[12.0, 54.0], [15.5, 58.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run