Bin a feature into equal-width buckets learned on train

Why it matters Bucketing ages, incomes or prices is a common feature step for scorecards and linear models, and edge handling is where pipelines break in production.

Equal-width binning turns a number into a bucket id, which helps linear models learn step-shaped effects.

Write uniform_bins(train, test, n_bins). Learn edges = np.linspace(min(train), max(train), n_bins + 1). Return (edges, idx) where idx is an int array giving the bucket of every test value in 0..n_bins - 1. A value exactly on an inner edge goes to the upper bucket. Values below the train min go to bucket 0 and values at or above the train max go to bucket n_bins - 1.

Signaturedef uniform_bins(train, test, n_bins)

Example

train [0, 10, 4, 6], test [0, 2.5, 5, 10, 12, -3], n_bins 4 gives edges [0, 2.5, 5, 7.5, 10] and idx [0, 1, 2, 3, 3, 0].

Understand the idea

Equal-width binning cuts the training range into n_bins pieces of the same width, like marking a ruler every 2.5 cm, and then reports which piece each value falls in.

Worked example: train min 0 and max 10 with 4 bins gives edges 0, 2.5, 5, 7.5, 10. Value 2.5 sits exactly on an edge and goes to the upper bucket, 1. Value 10 is the max and belongs to the last bucket, 3, not to a non-existent bucket 4. Value 12 is beyond the training range, so it also goes to 3, and -3 goes to 0.

Rule: edges = linspace(min, max, n_bins + 1); bucket = number of inner edges that are <= x.

The tricky part is the ends: a naive floor formula gives bucket n_bins for the max and negative ids for small values. Use searchsorted on the inner edges and both ends are handled for free. Learn edges once on train and keep them fixed.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleuniform_bins([0, 10, 4, 6], [0, 2.5, 5, 10, 12, -3], 4)
  • Sample 2: two binsuniform_bins([1, 3], [1, 2, 2.9, 3], 2)
  • Test 3: agesuniform_bins([18, 60, 25, 33, 47], [18, 29.9, 30, 59, 75], 3)