Feature Scaling
A distance calculation can be dominated by a feature simply because its numbers are larger. We will look at how scaling changes that calculation and why some models are affected more than others.
14 sections · 13 questions · 4 coding challenges
The arrow keys move between sections too.
Why Should Changing Units Change a Model?
BOTIE
As neural networks became practical to train, input preparation became an explicit part of training advice. LeCun and colleagues' 1998 Efficient BackProp discussed centring inputs and bringing their scales into a comparable range. The concern was practical: a learning procedure should not struggle merely because one coordinate is expressed with much larger numbers than another.
Scaling gives us a deliberate choice of units. Standardisation uses the training group's mean and spread; other methods choose a fixed interval. This can make distance comparisons more sensible and gradient steps better balanced. We retain the training transformation for later observations, because a new input must be measured with the same ruler as the examples that fitted the model.
Sources for this history
The Same Person, a Different Unit, a Different Answer
Rewrite someone's height from metres into centimetres. The person stays the same, but the number becomes much larger. A distance calculation can suddenly give height much more influence.
Scaling lets us choose how numerical differences should enter a model instead of letting recording units make that choice silently.
The person is different from the written number
A unit conversion changes the record without changing the observation. We should understand whether our prediction rule is meant to notice that change.
Metres
- 1.70
Centimetres
- 170
Scaling is part of defining the input
The detailed lesson compares specific transformations and the models that notice them. The goal is a sensible representation, not a universally best scaling rule.
Evaluate preprocessing together with fitting. Scaling alone does not establish which feature matters for prediction.
Explore the full example
Compare the raw and transformed values. Pay attention to how one large observation changes the scale and how the model's answer responds.
Each row is the same values after one method. The amber dot is the same value in every row, and a hollow arrow is a value that fell off the end of that ruler.
Part 1. When the Unit Decides
1. Two columns, two units
The crowd is eleven people, five children and six adults, with heights between 118 and 183 centimetres and weights between 24 and 83 kilograms. A model that asks how far apart two people are adds up the gap in each column, squared, and the height gap is counted in centimetres while the weight gap is counted in kilograms, as if a centimetre and a kilogram were the same size. Nothing in the arithmetic knows they are not.
distance² = (height gap)² + (weight gap)²The nearest person to a 150 cm, 45 kg query
The nearest person is three centimetres away in height and four kilograms away in weight. Changing the height unit changes its numerical contribution to Euclidean distance.
centimetres: distance² = 3² + 4² = 25
height share = 9 / 25 = 0.36
millimetres: distance² = 30² + 4² = 916
height share = 900 / 916 ≈ 0.98
metres: distance² = 0.03² + 4² = 16.0009
height share = 0.0009 / 16.0009 ≈ 0.00006The people did not change. The numerical weight given to height changed from almost none of the distance to almost all of it. Scaling makes that choice explicit instead of leaving it to the measurement units.
Keep in mind
2. The neighbours change with the unit
Now let the unit decide a real question. A person of 150 cm and 60 kg is put to the crowd and their three nearest neighbours vote on whether they are a child or an adult. The widget takes that vote four times, with the heights written in millimetres, in centimetres and in metres, and then with both columns standardized so that each is measured in its own spreads. Drag the green query about to find the people the four readings disagree on.
…
The vote at 150 cm and 60 kg
In millimetres the three nearest are the people at 147, 145 and 156 cm, whose weights are 41, 57 and 53 kg, and the vote is two children to one adult, so the answer is child. Height’s share of the squared distance to each of them is between 0.71 and 1.00, so weight had almost no say.
In centimetres the nearest are the 145, 156 and 159 cm people and the vote goes two adults to one, so the answer is adult. In metres the height column is worth nothing, the share falls below 0.015, and the three nearest are the people weighing 61, 57 and 57 kg, an adult again. Standardized, height is divided by 22.8 and weight by 20.8, the two columns have comparable numerical scales, and the answer is adult by the same two-to-one vote over a fourth set of neighbours.
Keep in mind
3. The walk slows with the unit
A model fitted by walking downhill feels the unit differently. Predicting weight from height by gradient descent means stepping down a bowl with one direction for the line’s level and one for its slope, and how steeply the bowl curves along the slope direction is set by the mean of the squared centred heights, a number that is 521.8 in centimetres, ten thousand times smaller in metres, and one hundred times larger in millimetres.
The level direction always curves at one. One step size has to serve both directions, so it is set by the steeper one and crawls along the shallower.
curvature along the slope = mean of (height − mean height)²
condition number = steeper curvature / shallower curvature…
Passes to converge, each at half its own divergence threshold
Standardized, both directions curve at exactly one, the condition number is one, and the walk reaches the line in two passes. In metres the slope direction curves at 0.052, the condition number is 19.2, and it takes 374 passes. In centimetres the condition number is 521.8 and it takes 8415. In millimetres it is 52,178, the safe step is 0.0000096, and after twenty thousand passes the walk had the slope right and had moved the level only to 17.0 of the 53.4 it was heading for, so the fit stopped at its cap and reported itself unfinished.
Every row walked at its own best safe rate, so what the table compares is the shape of the bowl under each unit.
Keep in mind
Part 2. One Map, Two Numbers
4. Subtract a centre, divide by a spread
Every correction on this page is one line of arithmetic, applied to each column on its own. Pick a number to call the column’s centre and a number to call its spread, take the centre away from every value, and divide what is left by the spread. What a method learns from a column is those two numbers and nothing else, and what it does to a value is this.
scaled = (value − centre) / spreadThe playground at the top of the page is that line drawn five times. The top row holds one column of raw values, and each row beneath it is the same column after one choice of centre and spread, printed at the left. The amber dot is the same value in every row, so the rows are five rulers laid against one number, and the readouts at the right are that number read on five rulers.
Keep in mind
5. Five readings of the same two numbers
What differs between the five methods is only where the centre and the spread are read from, and the whole family fits in a table.
standardize centre = mean spread = standard deviation
min-max centre = smallest value spread = largest − smallest
max-abs centre = 0 spread = largest magnitude
robust centre = median spread = third quartile − first quartile
root mean square centre = 0 spread = √(mean of the squares)Each row is an answer to a different worry. Standardizing leaves a column with mean zero and spread one, so a coefficient fitted on it says how much the target moves per standard deviation of that column, which can be compared across columns. Min-max lands everything in the unit interval, which is what an image pipeline or a bounded activation wants.
Max-abs divides without centring, so a zero stays a zero, a sparse column stays sparse and the sign survives. Robust reads the median and the quartiles, which never look at the ends of the column. Root mean square divides by magnitude about zero and keeps the level, on the view that a column’s level is information.
Keep in mind
6. The five readings by hand
Press the five readings button, five values of 9, 19, 24, 29 and 39, chosen so that every centre and spread comes out as a whole number. The mean first.
9 + 19 + 24 + 29 + 39 = 120, 120 / 5 = 24Worked example
The deviations from 24 are −15, −5, 0, 5 and 15, whose squares are 225, 25, 0, 25 and 225. Their mean is the variance and its square root is the standard deviation, so standardizing reads a centre of 24 and a spread of 10, which is what the first row prints. Root mean square runs the same sum on the values themselves rather than on their deviations, and its spread comes out at 26.
225 + 25 + 0 + 25 + 225 = 500, 500 / 5 = 100, √100 = 10
81 + 361 + 576 + 841 + 1521 = 3380, 3380 / 5 = 676, √676 = 26The other scalers use different definitions of centre and spread. For these five sorted values, the middle is 24 and the two quartiles are 19 and 29.
min-max: centre = 9; spread = 39 − 9 = 30
max-abs: centre = 0; spread = 39
robust: centre = 24; spread = 29 − 19 = 10Put the value 39 through each scaler to compare how those choices affect the result.
(39 − 24) / 10 = 1.5
(39 − 9) / 30 = 1.0
39 / 39 = 1.0
(39 − 24) / 10 = 1.5
39 / 26 = 1.5The readouts at the right say 1.50, 1.00, 1.00, 1.50 and 1.50. Standardize and robust agree here by coincidence rather than by rule, since the sample is symmetric, so its median is its mean, and its two quartiles happen to be exactly one standard deviation apart. The outlier button breaks that coincidence at once, and Part 3 says how.
7. What standardizing promises
What a method promises is whatever its map fixes, and standardizing promises a mean of exactly zero and a variance of exactly one. Three lines show why. Write m for the mean and s for the population standard deviation, so that s² is the mean of the squared deviations, and put every value through the map.
zᵢ = (xᵢ − m) / s
mean(z) = (1/n) Σ (xᵢ − m) / s = (1/s) · (m − m) = 0
var(z) = (1/n) Σ (xᵢ − m)² / s² = s² / s² = 1›Why this works
The first line is the map. The second says the deviations from a mean always cancel, the statistics primer’s balance point, so dividing them by anything still leaves a mean of zero. The third is the whole argument. The mean of the squared deviations is s² by definition, and dividing every deviation by s divides that mean by s², which leaves exactly one.
Keep in mind
Part 3. Five Rulers Against One Outlier
8. What the other four promise
The same move reads the promise off every other row of the table. Min-max sends the smallest training value to 0 and the largest to 1 and fixes nothing in between. Max-abs sends the value of largest magnitude to 1 or −1 and leaves zero where it was. Robust sends the two quartiles to points exactly one apart, at whatever position the median leaves them, so the middle half of the column always spans one unit.
Root mean square makes the mean of the squared scaled values one, since it divided by the square root of exactly that mean.
Keep in mind
9. One wild value sets the range
Press the outlier button on the playground and the 39 becomes 99. The mean jumps from 24 to 36, the min-max spread from 30 to 90 and the max-abs spread from 39 to 99, so under those two methods the four ordinary values are squashed into the first third of the ruler, the 29 landing at 0.22 under min-max and at 0.29 under max-abs. The standardize row shifts as well, since both the mean and the standard deviation feel the new value.
| method | centre, five readings | spread, five readings | centre, with the 99 | spread, with the 99 |
|---|---|---|---|---|
| standardize | 24 | 10 | 36 | 32.2 |
| min-max | 9 | 30 | 9 | 90 |
| max-abs | 0 | 39 | 0 | 99 |
| robust | 24 | 10 | 24 | 10 |
| root mean square | 0 | 26 | 0 | 48.3 |
The three rows that read the ends of the column move; the one that reads its middle does not.
Keep in mind
10. The median and the quartiles never looked
The robust row still prints a centre of 24 and a spread of 10. The median and the quartiles are positions in the sorted list, and replacing the largest value with a larger one changes no position, so the 99 lands at 7.5, far off the end of that ruler, while the other four are precisely where the five readings left them.
(99 − 24) / 10 = 7.5One method is honest about the outlier by moving everything. Another is honest about it by moving nothing except the outlier. Which honesty you want depends on whether the wild value is a measurement or a mistake, and a scaler cannot know which, so the choice is yours and the page can only show what each choice costs.
Keep in mind
11. Where the quartiles land
A quarter of the way along a sorted list is rarely a whole position, so a rule is needed for what the first quartile of eleven values means. The rule followed here, and by most others, reads the quartiles at a quarter, a half and three quarters of the last index, interpolating between two neighbours when the position is not whole.
Five values have a last index of four, so the cuts fall at 1, 2 and 3, exactly the second, third and fourth values. Eleven values have a last index of ten, so they fall at 2.5, 5 and 7.5.
…
The crowd's eleven heights
The sorted heights are 118, 120, 122, 145, 147, 156, 159, 162, 178, 180 and 183. With the interpolation convention used here, the lower quartile lies halfway between 122 and 145; the upper lies halfway between 162 and 178.
lower quartile = (122 + 145) / 2 = 133.5
median = 156
upper quartile = (162 + 178) / 2 = 170
interquartile range = 170 − 133.5 = 36.5The robust scaler therefore uses 156 as the centre and 36.5 as the spread.
Keep in mind
12. A height typed in millimetres
The outlier the crowd is likely to meet is a mistake of units, one person’s height entered as 1830 because the form said millimetres. The widget puts the crowd’s eleven heights through the five rulers as measured, then with the tallest person typed as 1830, then with a middle person, the 147, typed as 1470. The amber dot is the 156 cm person, the median, whom each method ought to leave alone.
…
The amber dot is the 156 cm person, and the readout at the right is where each ruler puts them. The rose dot is the typed value, when there is one.
The tallest typed as 1830
As measured, the heights have a mean of 151.8 and a standard deviation of 22.8, a range of 65 from 118, a largest magnitude of 183, a median of 156 with an interquartile range of 36.5, and a root mean square of 153.5. With the 183 typed as 1830 the mean goes to 301.5 and the deviation to 483.8, the range to 1712, the largest magnitude to 1830 and the root mean square to 570.1, so the median person, who read 0.58 on the min-max ruler, now reads 0.02, squashed with everyone else into the first four percent of the interval.
The robust row still reads 156 and 36.5, the median person still reads 0.00, and the 1830 lands at 45.86 on that ruler, which is where a value 45 interquartile ranges above the median belongs.
Keep in mind
13. Root mean square keeps the level
The last row of the playground looks like standardizing with a different spread, and on a column centred at zero that is exactly what it is, since the root mean square of a zero-mean column is its standard deviation. The crowd’s heights are nowhere near zero. Their root mean square is 153.5, almost the mean of 151.8, because when every value is about 150 the magnitude about zero is about 150.
root mean square = √(mean of height²) = 153.5
standard deviation = √(mean of (height − 151.8)²) = 22.8The crowd's heights on the two rulers
Dividing by 153.5 puts every height between 0.77 and 1.19, all bunched near one, with the shortest child and the tallest adult 0.42 apart. Standardizing puts the same people between −1.48 and 1.37, 2.85 apart. The first ruler kept the fact that everyone is about a metre and a half tall and had little room left for the differences between them, where standardizing removed the shared level first and used the whole ruler for the differences.
Keep in mind
Check yourself
Questions on Parts 1 to 3
Question 1 of 5
The nearest person is three centimetres away in height and four kilograms away in weight. Written in millimetres instead, what share of the squared distance does height carry?
Part 4. Fit Once, Apply Everywhere
14. Learned on the training rows
A scaler is fitted like any model, and what it learns is its centre and spread, read from the rows it was shown. Those two numbers are then reused, unchanged, on every row that comes later, whether that row is a held-out person, a new person next year, or the same training row put through again. The widget below lets you hold people out of the crowd and watch what the remaining rows teach the scaler and where the held-out rows then land.
heights, cm
…
The three tallest held out
With the three tallest adults held out the training rows have a mean height of 141.1 and a deviation of 17.2. The held-out heights of 180, 183 and 178 standardize with those numbers to 2.26, 2.43 and 2.14, a mean of 2.28, which is the right answer. They are more than two spreads above the people the fit saw, and the scaled numbers say so.
Keep in mind
15. Why recomputing on held-out rows is wrong
The tempting alternative is to standardize the held-out rows with their own mean and deviation, and the widget’s second number line does exactly that. The three tallest people, standardized against each other, come out at −0.16, 1.30 and −1.14, which announces that one of them is shorter than average, and the only average they were measured against was their own. The scaler has been refitted on rows the model never saw, which is the leak, and the numbers it produces are on a different scale from the one anything downstream learned.
A line reading both scales
The line fitted on the eight training rows expects height standardized using the training mean and standard deviation.
predicted weight ≈ 43.3 + 14.0 × standardized heightUsing those training statistics, its predictions for the three held-out people are 74.8, 77.2 and 73.1 kilograms, against actual weights of 80, 83 and 78. Standardizing those same people with their own statistics instead produces 41.0, 61.4 and 27.4 kilograms. The last prediction is for an adult who actually weighs 78 kilograms.
The mismatch is smaller when the held-out group happens to have a similar mean and spread to the training group. That coincidence cannot make the procedure correct. New inputs must use the coordinate system in which the model was fitted.
Keep in mind
16. Matching by name, a subset or the exact set
A scaler learns one centre and spread per named column, and a transform matches the columns it is handed by name and never by position, so features may arrive in any order. Two rules follow, and they differ from the rule a model’s predict follows. A scaler fitted on height and weight will transform height alone, since scaling one column of a held-out set is a legitimate thing to want, and measured, a one-column request came back with one column.
It refuses a column called age that it never saw, because a column the fit never saw has no centre and no spread, and inventing one would answer a question nobody asked.
| handed to a scaler fitted on height and weight | answer |
|---|---|
| height only | accepted, one scaled column back |
| weight, height, in that order | accepted, matched by name |
| height and age | refused by name, never learned a scaling for age |
| age, to the inverse transform | refused by name, the same way |
A subset is fine; an unknown name is not. A model's predict is stricter and demands the exact set, since a missing column makes its plane unevaluable.
Keep in mind
17. Back to the original units
Because the map is a subtraction and a division, undoing it is a multiplication and an addition, and every scaler here has an inverse that reads an answer back in the units the data came in.
value = scaled × spread + centre…
On the crowd’s heights the round trip is exact to the last bit for standardizing, min-max and robust, and off by 14 and 28 quadrillionths of a centimetre for max-abs and root mean square, which is one or two units in the last place of a number near 150 and is what dividing and then multiplying by the same number costs. The same arithmetic translates a coefficient. A line fitted on standardized height has a slope in kilograms per standard deviation, and dividing by the deviation gives kilograms per centimetre.
slope in cm = slope in z / spread
intercept in cm = intercept in z − slope in cm × centreThe standardized line on the crowd, translated back
On standardized height, least squares gives a slope of about 20.33 kilograms per standard deviation and an intercept of about 53.36 kilograms. To express the same line in centimetres, divide the slope by the training standard deviation and adjust the intercept.
slope in cm = standardized slope / height standard deviation
≈ 20.33 / 22.84 ≈ 0.8901 kg/cm
intercept in cm = mean weight − slope in cm × mean height
≈ 53.36 − 0.8901 × 151.82 ≈ −81.77 kgThe displayed inputs are rounded; the fit uses the full values. Fitting the raw heights directly gives the same line. Only the coordinates used to describe it have changed.
Keep in mind
Part 5. Which Models Care
18. Anything that measures a distance
Part 1 measured it on a nearest-neighbour vote, and the same sum of squared column gaps is inside k-means, whose centres are chosen by it, and inside principal component analysis, whose first direction follows whichever column has the largest variance in whatever unit it was recorded in. Every one of these reads a column’s unit as its importance, because the unit is a factor on every gap in that column and the square of a factor on every squared gap.
Keep in mind
19. Anything that walks
Step 3 measured it on gradient descent. Two passes standardized, 374 in metres, 8415 in centimetres, and an unfinished walk in millimetres, all to the same line, and the difference was the shape of the bowl. A network trained by the same descent has this problem at every layer, which is why the normalisation layers exist, standardizing inside the network what feature scaling standardizes at its door.
Keep in mind
20. Anything that penalises a coefficient
Ridge adds the squared size of every coefficient to what it minimises, and the size of a coefficient depends on the unit its column is in. A column recorded in metres needs a coefficient one hundred times larger than the same column in centimetres to do the same work, so its squared penalty is ten thousand times as large, and the fit reports that accident of bookkeeping as a fact about the data.
…
Weight against height at a penalty of one
In centimetres the ridge coefficient is 0.890 kg per centimetre, next to the least-squares 0.890, and the fit scores 0.9588. In metres the coefficient should be 89.0 and the penalty holds it to 32.5, and the score collapses to 0.5718 on the same eleven people. In millimetres the coefficient is 0.0890 and the penalty barely touches it. Standardized, the coefficient is 18.6 kg per standard deviation against a least-squares 20.3, and the score is 0.9521.
Keep in mind
21. Trees do not notice
A decision tree never notices. Every split asks whether a value is above a threshold, and the rows that go left when asked about 151.5 centimetres go left when asked about 1515 millimetres, because any rescaling that keeps the order moves the threshold along with the values.
…
The same tree four times
On the crowd the tree is one question deep with two leaves under every unit, its root asks whether height is below 151.5, or 1515, or 1.515, or −0.014 standard deviations, and its eleven predictions are identical down the table. The tree, its leaves and its accuracy are the same before and after, which is why the tree pages and the ensembles built on them never scaled anything.
Keep in mind
22. Least squares does not notice either
Plain least squares is equivariant to the unit, and the word means that the answer changes in exactly the way the unit did. Measure height in metres instead of centimetres and the slope is multiplied by one hundred, the intercept, the fitted weights, the residuals and the R² are untouched, and the line is the same line.
…
The crowd's line in four units
The slope is 0.8901 in centimetres, 89.01 in metres and 0.08901 in millimetres, the intercept is −81.77 in all three, and the R² of 0.9588034 agrees across all four rows to better than a billionth. Translated back, the standardized row gives the same 0.8901 and −81.77.
Keep in mind
Check yourself
Questions on Parts 4 and 5
Question 1 of 5
Three tall adults are held out, then standardized with their own mean and deviation rather than the training ones. What comes back?
Part 6. Implementation and Failure Contracts
23. What a scaler must specify
A complete implementation states how the centre and the spread are read, including the population or sample divisor for a standard deviation and the interpolation rule for a quartile; that the fit reads the training rows only and the transform reuses those numbers; how columns are matched, which is by name here, and whether a subset is accepted; what a zero spread does, which is refuse rather than substitute a one; that an inverse exists and what its round trip costs; and what happens to a value outside the fitted range, which is that it is scaled by the same map and lands wherever that puts it.
Keep in mind
24. The edges, each one asked
Every row below was tried rather than reasoned about, and the widget under the table tries the same list again on every load, so the table cannot go stale without the widget saying so.
| the edge | the behaviour |
|---|---|
| no features at all | refused before anything is read, since there is nothing to learn a centre from. |
| an empty column | refused, since a column is required to hold at least one value. |
| one row | refused by standardize, min-max and robust, whose spread is zero on one value; accepted by max-abs and root mean square, which read a spread of 170 from a lone 170 and send it to 1. |
| a constant column | the same split. Three refuse a spread of zero by name; max-abs and root mean square accept a constant 170 and answer a constant 1, and refuse only a column of zeros. |
| a missing or infinite value | refused where the column is built, before any scaler sees it. |
| six identical values of eight, for robust | accepted, with an interquartile range of 0.75, since the third quartile lands just past the run. |
| seven identical values of eight, for robust | refused for a spread of zero, though the column is not constant; both quartiles fall inside the run. Nine of twelve is accepted and ten of twelve refused, so the rule is about three quarters. |
| nine values a machine epsilon apart | accepted, and scaled to between −1.55 and 1.55 by standardizing and to 0 to 1 by min-max; a spread of 2.6 × 10⁻¹⁶ is a spread. |
| a subset of the fitted features | accepted; one column in, one column out, matched by name. |
| a feature the fit never saw | refused on the way in and on the way back alike, and the message names what was learned and what was handed over. |
| transform before fit | refused, and the message says the scaler has not been fitted rather than reporting some missing attribute. |
| two features with one name, or of different lengths | refused when the columns are gathered, before any scaling is read. |
| a value beyond the fitted range | accepted; 250 cm through a min-max scaler fitted on 118 to 183 answers 2.03. |
…
25. Documented rather than defended
The table exposes four separate numerical decisions. We should understand what each one allows before treating every accepted column as suitable for modeling.
- A very small positive spread is accepted. Scaling can therefore magnify tiny differences, including differences caused by rounding or measurement noise.
- A constant nonzero column can pass through max-absolute or RMS scaling because the divisor is nonzero. It remains constant afterward and still provides no variation.
- Robust scaling is refused when the interquartile range is zero. A column can contain some differing observations while its middle half still has no measurable spread.
- A new value outside the fitted range is transformed without clipping. It can therefore appear outside the training output range, preserving evidence that it differs from the fitted examples.
Keep in mind
Check yourself
Questions on Part 6
Question 1 of 3
Which of these edges does the library accept rather than refuse?
More than one of these may hold. Submit when you have them all.
Try it with Botie
Build with Botie
Write and run Python