Binning and log transforms
Quick answer
Binning maps a continuous value into an interval; a logarithm compresses large positive values. These transforms change the representation of a feature, not its underlying measurement. Choose them to express plausible relationships or improve numerical behavior.
Fixed interval edges
from bisect import bisect_rightprint([bisect_right([10,20], x) for x in [9,10,19,20]])Expected output:
[0, 1, 1, 2]The insertion index equals the number of edges not greater than x.
How it works
For fixed edges 10 and 20, define bins x < 10, 10 <= x < 20 and x >= 20. A boundary belongs to the upper interval in this convention. Learn quantile-based or uniform edges using training rows only, and store them for future inputs. Repeated quantile edges can collapse bins; inspect the resulting count. An ordinal bin code can imply equal spacing in a linear model; one-hot bins avoid that assumption but use more columns. For nonnegative counts, log1p(x) computes log(1+x), including zero, and is numerically preferable to log(1+x) near zero. Its real domain is x > -1; negative measurements need domain-specific treatment, not arbitrary shifts. Log transforms compress high values but do not guarantee normality. A transform of the target is a separate decision; exponentiating a predicted mean log target does not generally recover the original-scale conditional mean.
Log compression
from math import log1pprint([round(log1p(x), 3) for x in [0,9,99]])Expected output:
[0.0, 2.303, 4.605]A tenfold increase in 1+x adds a constant log increment.
Common mistakes
Never compute quantile edges separately on validation data. An input exactly equal to an edge must follow the documented boundary rule. Do not silently clip invalid negative counts merely to make logarithms run.
Practice
Assign 9, 10, 19, 20 to bins with edges 10 and 20. Explain why 10 and 20 move to the higher bin. Compare the spacing of counts 0, 9 and 99 before and after log1p. Complete the chapter exercise and knowledge check. Scientific examples are local scikit-learn 1.8.0 static snippets; ByteMind execution support is not verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Binning and log transforms — knowledge check
Apply feature engineering and leakage controls to synthetic scenarios.
Which bin contains 20 for edges 10 and 20, upper-inclusive assignment at edges?
Where should learned quantile edges be fitted?
What is log1p(0)?
Which value is outside the real domain of log1p?
What is a risk of ordinal bin codes in a linear model?