Binning (also called discretization) converts continuous numeric features into discrete categories by dividing the value range into equal-width intervals. Each value is assigned to its corresponding bin. This technique can reduce noise, handle outliers, and make features compatible with algorithms that work better with categorical data.
Given a list of numeric values and a number of bins, assign each value to a bin index using equal-width binning.
The maximum value is clamped to the last bin. If all values are equal, all are assigned to bin 0.
Input:
values = [0, 25, 50, 75, 100], num_bins = 4
Output:
[0, 1, 2, 3, 3]
Range is 100, width = 25. Bins: [0-25), [25-50), [50-75), [75-100]. Value 100 is clamped to bin 3.
Input:
values = [1, 2, 3, 4, 5, 6], num_bins = 2
Output:
[0, 0, 0, 1, 1, 1]
Range is 5, width = 2.5. Values 1-3 fall in bin 0 [1, 3.5), values 4-6 fall in bin 1 [3.5, 6].
Compute min_val and max_val. If they are equal, return all zeros. Otherwise compute bin_width = (max_val - min_val) / num_bins. For each value, compute int((v - min_val) / bin_width) and clamp to num_bins - 1.
The clamping with min(bin_idx, num_bins - 1) is needed because the maximum value exactly equals max_val, and (max_val - min_val) / bin_width = num_bins, which would be out of range.
Sign in to take notes on this problem
Accepts: array
Accepts: number
Binning (also called discretization) converts continuous numeric features into discrete categories by dividing the value range into equal-width intervals. Each value is assigned to its corresponding bin. This technique can reduce noise, handle outliers, and make features compatible with algorithms that work better with categorical data.
Given a list of numeric values and a number of bins, assign each value to a bin index using equal-width binning.
The maximum value is clamped to the last bin. If all values are equal, all are assigned to bin 0.
Input:
values = [0, 25, 50, 75, 100], num_bins = 4
Output:
[0, 1, 2, 3, 3]
Range is 100, width = 25. Bins: [0-25), [25-50), [50-75), [75-100]. Value 100 is clamped to bin 3.
Input:
values = [1, 2, 3, 4, 5, 6], num_bins = 2
Output:
[0, 0, 0, 1, 1, 1]
Range is 5, width = 2.5. Values 1-3 fall in bin 0 [1, 3.5), values 4-6 fall in bin 1 [3.5, 6].
Compute min_val and max_val. If they are equal, return all zeros. Otherwise compute bin_width = (max_val - min_val) / num_bins. For each value, compute int((v - min_val) / bin_width) and clamp to num_bins - 1.
The clamping with min(bin_idx, num_bins - 1) is needed because the maximum value exactly equals max_val, and (max_val - min_val) / bin_width = num_bins, which would be out of range.
Sign in to take notes on this problem
Accepts: array
Accepts: number