Exercises — Binning and discretization
Two symbols recur, so let us pin them down once, in plain words, before anything else:
The figure below is the mental picture to keep for every exercise on this page: notice the six teal fence-posts labelled but only five orange gaps between them. Whenever a problem asks for edges vs. bins, re-run this picture in your head — the top arrow counts posts, the bottom arrow counts gaps.

Two more conventions we will lean on repeatedly, so let us fix them now:
Level 1 — Recognition
L1.1 · Which strategy?
You have website session-duration data in seconds: most sessions are 5–60 s, but a handful last hours. You want 4 bins that each hold roughly the same number of sessions. Name the binning strategy.
Recall Solution
Equal-frequency (quantile) binning. The phrase "each hold roughly the same number of sessions" is the definition of equal-frequency. Equal-width would put nearly everything in the first bin because the data is skewed by the multi-hour outliers.
L1.2 · Count the edges
You build 5 bins. How many bin edges are there?
Recall Solution
6 edges. There is always one more fence-post than gaps: edges create 5 gaps (bins). Formula: bins edges.
L1.3 · Which bin?
Edges are (the final means "no upper cap", as defined above) with the last-bin-includes-its-left-edge convention. Which bin (1–4) does income fall into?
Recall Solution
Bin 3, . The rule is . Since is the left edge of bin 3, it belongs to bin 3, not bin 2 whose right edge is excluded. (For the record, the top bin here is — any income of or more, with no ceiling, so even a billionaire has a home.)
Level 2 — Application
L2.1 · Equal-width edges
Data range: , . Build equal-width bins. Give the bin width and all edges.
Recall Solution
What we do: split the range into 4 equal pieces.
- Range .
- Width .
- Edges : .
So the 4 bins are . Why equal-width? Because we were given nothing about density — we only partition the number line, ignoring how many points sit where.
L2.2 · Equal-frequency edges
Sorted data: (). Build equal-frequency bins. Give the interior edges (the three cut-points).
Recall Solution
What we do: each bin should hold points, so we cut between the 2nd-and-3rd, the 4th-and-5th, and the 6th-and-7th sorted values. The fence goes at the midpoint of each such pair.
- Between value 2 () and value 3 (): cut .
- Between value 4 () and value 5 (): cut .
- Between value 6 () and value 7 (): cut .
Interior edges . Check the bins:
- Bin 1 : — only 1 point, because two values equal and the fence sits exactly on them, pushing both s right.
- Bin 2 : — 3 points.
- Bin 3 : — 2 points.
- Bin 4 : — 2 points.
Why not exactly 2-2-2-2? The tie at lands on a fence-post. Because bins are left-closed / right-open, both s fall into the bin on their right, so the target count cannot be met exactly. Perfect balance is a target, not a guarantee, whenever values are tied on an edge — a preview of the mastery-level problem L5.2.
L2.3 · Sturges' rule
You have samples. How many bins does Sturges' rule suggest?
Recall Solution
Sturges: . Here , so bins. Why ? Each bin edge is one binary "above/below" split; with splits you distinguish patterns, and setting gives .
Level 3 — Analysis
L3.1 · Diagnose the empty bin
Data , equal-width, . Show the bins and explain why one is empty.
Recall Solution
, , edges .
- : → 5 points
- : → 0 points
- : → 1 point
Why empty? Equal-width places fence-posts by distance, not by data. The lone outlier stretches the range so wide that the two lower posts land in a region where no data lives. The middle bin is empty because there simply are no values between 34 and 67.
L3.2 · Same data, equal-frequency
Repeat L3.1 with equal-frequency, , . Give the bins.
Recall Solution
Target per bin. Sorted: .
- Cut between 2nd () and 3rd () → edge ; cut between 4th () and 5th () → edge .
- Bin 1 : ; Bin 2 : ; Bin 3 : .
Analysis: every bin now holds 2 points — the outlier is quietly absorbed into the top bin instead of blowing up the geometry. This is exactly the outlier robustness the parent note promised. See 2.3.01-Handling-missing-data for the sibling idea of taming bad values.
L3.3 · Bias–variance direction
As you increase (more, narrower bins), does model bias go up or down? Does variance? One sentence each.
Recall Solution
- Bias goes DOWN. Narrower bins hug the true curve better — less "flatness" assumed inside each bin.
- Variance goes UP. Each bin now holds fewer points, so its label is more swayed by individual noise.
This is the classic tug-of-war; details in 4.3.02-Bias-variance-tradeoff.
Level 4 — Synthesis
L4.1 · Log-then-bin
Skewed income data spans \1{,}000$1{,}000{,}000$1$1000\log_{10}$ transform. Give the bin edges in actual dollar amounts.
Recall Solution
What we do: equal-width in log-space, then map back to dollars. To avoid unit confusion, we carry everything in thousands of dollars internally, then multiply by at the very end to report real dollars.
- Work in thousands: \1\to1$1000\to1000$.
- range: .
- Log-width . Log edges: .
- Map back with (still in thousands): .
- Multiply by to get actual dollars: \ \1{,}000,\ $10{,}000,\ $100{,}000,\ $1{,}000{,}000$.
Edges in real dollars: [\1{,}000,\ $10{,}000,\ $100{,}000,\ $1{,}000{,}000][$1\text{k},$10\text{k})[$10\text{k},$100\text{k})[$100\text{k},$1000\text{k}]$9$90$900$k wide) — but that is exactly what skewed data needs: wide bins where data is sparse (the rich tail), narrow where it is dense (the low end). Equal-width in log-space is a cheap way to get near-equal frequency in original space.
L4.2 · Pipeline ordering
You will do 5-fold cross-validation with equal-frequency binning. Write the correct order of the two operations (fit quantiles / split into folds) and explain in one line why.
Recall Solution
Correct order: split into folds first, then fit the quantile edges on the training fold only, and apply those same edges to the held-out fold. Why: if you compute quantiles on the whole dataset first, the test fold's values secretly influenced the edges — that is leakage and it inflates your score. Fit on train, transform test.
L4.3 · Trees don't need it (mostly)
Your teammate one-hot-encodes (2.2.03-One-hot-encoding) binned features and feeds them to a decision tree (3.1.04-Decision-trees). Why is binning-before-trees often redundant, and when is it still useful?
Recall Solution
Redundant because: a decision tree already chooses its own split thresholds on the raw continuous feature — it is essentially learning optimal bin edges automatically. Pre-binning just freezes those edges to your (possibly worse) choices. Still useful when: (a) you want the same human-interpretable buckets across many models/reports, (b) you deliberately encode domain thresholds the tree might not find with limited data, or (c) you are enabling 2.1.09-Feature-interactions between coarse categories.
Level 5 — Mastery
L5.1 · Degenerate: all values identical
Data . What happens with equal-width ? With equal-frequency ? How should code handle it?
Recall Solution
- Equal-width: , so width . All edges collapse to ; the bins are empty degenerate intervals. Division is fine () but the result is meaningless.
- Equal-frequency: every quantile of a constant is , so all interior edges equal — again collapsed. You cannot make 3 non-empty bins from one distinct value.
- Handling: detect (zero variance) and either drop the feature or emit a single bin. Robust libraries either merge duplicate edges or raise a warning; never trust silent output.
L5.2 · Duplicate quantile edges
Sorted data , equal-frequency . The lower quantiles all land on . What breaks, and what is the standard fix?
Recall Solution
Target per bin ⇒ cut between the 2nd-and-3rd values and between the 4th-and-5th values. But positions 1–5 are all , so:
- Cut between value 2 () and value 3 (): midpoint .
- Cut between value 4 () and value 5 (): midpoint .
Both interior edges equal → duplicate edges → a zero-width, empty middle bin.
Standard fix: pandas.qcut(..., duplicates="drop"), which merges the duplicate edges. You
then get fewer bins than requested (here effectively 2: is empty and drops, leaving a
"" bin and a "" bin), which is correct — the data simply cannot support 3 equal-frequency
bins. Lesson: requested is an upper bound, not a guarantee, for equal-frequency on
discrete/heavy-tie data.
L5.3 · Information-loss sanity check
A feature is binarized (thresholded) into 2 equal-frequency bins on data . Compute the entropy of the bin labels (in bits) and state the information kept.
Recall Solution
Two equal bins each hold 2 of 4 points ⇒ probabilities . Why ? asks "2 to what power gives this number?" Since , the exponent is , so . Substituting: The label carries exactly 1 bit — the maximum possible for 2 outcomes. Every drop of order information below the median vs. above it is preserved; everything within each half is lost.
Recall Self-test: rebuild the ladder from memory
Equal-width divides the ::: number line (range) into equal pieces Equal-frequency divides the ::: data (puts equal counts per bin) bins require how many edges ::: Half-open bins mean a boundary value goes to the bin on its ::: right A value below the first edge (or above a finite ) gets ::: no bin (a "missing"/NaN label) unless you use edges or clip Fit quantile edges on which data during CV ::: the training fold only Sturges' rule formula :::