Search

Search papers and lessons

Feature Scaling

Level 2 · 11 min read

Feature scaling puts every input column on a similar range, so that no feature dominates a distance or a gradient just because its unit is large.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Calculus
  • Linear algebra
  • Learning basics
  • ReadReady to readNot yet

TL;DR

Feature scaling changes the numbers in each input column so that they sit on a comparable range, usually by subtracting a centre and dividing by a spread. The point is that a model should weigh its inputs for what they say, not for the unit they are measured in. This matters for any method that measures distance between examples or follows a gradient across features.

Builds on: Mean and Variance, Linear Transformation · Leads to: K-Nearest Neighbors, batch normalization

Where it's used

Nearest-neighbour search in a shop's recommendations. A system describes each product by its price in dollars and its weight in grams. A typical weight is a few hundred grams, while a typical price is tens of dollars, so the weight column carries numbers several times larger. A nearest-neighbour search would then judge products mostly by weight. Scaling both columns to a common range lets price and weight count fairly when the system looks for similar items.

Training a house-price model. A linear model learns one weight per feature. Floor area is measured in square metres, around 50 to 300, while the number of bedrooms is 1 to 5. Without scaling, the error surface is stretched along the area direction, and gradient descent must zigzag to reach the bottom. A Learning Rate that is safe for the area weight is far too slow for the bedroom weight, and a rate large enough for the bedroom weight can make the area weight oscillate or diverge.

Neural networks with mixed inputs. Deep networks often receive sensor readings in different units. Scaling the inputs first keeps early-layer activations in a sensible range, and batch normalization applies the same idea inside the network, one layer at a time.

How it works

Here is a single feature, measured on three samples, scaled with min-max scaling. Min-max scaling is the simplest choice: it maps the smallest value to 0 and the largest to 1.

  1. Start. One feature has three values: 10, 20 and 40. These are the training values for this column.
  2. Find the range. The smallest value is 10 and the largest is 40. The range is 40 minus 10, which is 30. Check: the range is never negative, and it is zero only if all values are equal.
  3. Shift so the smallest is zero. Subtract 10 from every value: 0, 10 and 30. Check: the smallest value is now exactly 0.
  4. Divide by the range. Divide each shifted value by 30: 0, one third, and 1. Check: the largest value is exactly 1, and every value is between 0 and 1.
  5. Reuse the same numbers on new data. A new sample has the value 25. Subtract the training minimum 10 and divide by the training range 30: (25 minus 10) divided by 30 is one half. Check: the result is 0.5, which is between one third and 1, as expected for 25 between 20 and 40.
  6. Pass the scaled values to the model. The model never sees the raw 10, 20, 40. It sees 0, one third, 1 for the training samples and 0.5 for the new one.
flowchart LR
  T["Training column"] --> S["Compute centre and spread<br/>on training data only"]
  S --> A["Apply the same rule<br/>to training data"]
  S --> B["Apply the same rule<br/>to new data"]
  A --> M["Model trains on scaled values"]
  B --> M

Step 5 is the rule that people break most often. The centre and spread come from the training data, and the same two numbers are applied to every later sample.

The math

Let xx be one value of a feature, and let the training values of that feature be x1,…,xnx_1, \dots, x_n.

Definition: Min-max scaling

Let xmin⁡x_{\min} and xmax⁡x_{\max} be the smallest and largest training values. The scaled value is x′=(x−xmin⁡)/(xmax⁡−xmin⁡)x' = (x - x_{\min}) / (x_{\max} - x_{\min}). Values from the training set land in [0,1][0, 1].

Step 2 in symbols: the range

The range is xmax⁡−xmin⁡x_{\max} - x_{\min}. In the example, 40−10=3040 - 10 = 30.

Steps 3 and 4 in symbols: shift and divide

The formula subtracts the minimum first, then divides by the range. Each of these is a linear transformation of the form x↦ax+bx \mapsto a x + b, with a=1/(xmax⁡−xmin⁡)a = 1/(x_{\max} - x_{\min}) and b=−xmin⁡/(xmax⁡−xmin⁡)b = -x_{\min}/(x_{\max} - x_{\min}). That is why scaling leaves the order of values and the shape of their distribution unchanged. Only the units change.

Check for the example: a=1/30a = 1/30 and b=−10/30=−1/3b = -10/30 = -1/3. Then x=40x = 40 gives 40/30−1/3=4/3−1/3=140/30 - 1/3 = 4/3 - 1/3 = 1. Good.

Step 5 in symbols: a new sample

For a new value xnewx_{\text{new}}, use the same xmin⁡x_{\min} and xmax⁡x_{\max} from training. In the example, (25−10)/30=0.5(25 - 10)/30 = 0.5. If xnewx_{\text{new}} is outside the training range, the scaled value falls outside [0,1][0, 1]. For instance, xnew=50x_{\text{new}} = 50 gives (50−10)/30=4/3(50 - 10)/30 = 4/3. That is correct behaviour, not an error.

Standardization in symbols

The other common choice centres the feature at mean zero and gives it unit spread. Let μ\mu be the mean of the training values and σ\sigma their standard deviation, the square root of the average squared distance from μ\mu, as in Mean and Variance. Then

z=x−μσz = \frac{x - \mu}{\sigma}

Scaled values have mean 0 and standard deviation 1 on the training set. Min-max scaling is sensitive to a single extreme value, because one outlier moves xmax⁡x_{\max} and squeezes all the other values. Standardization is less affected by one outlier, but it does not bound the output to [0,1][0, 1].

Why the units matter

Suppose two features are uu and vv, and a model uses the Euclidean distance (u1−u2)2+(v1−v2)2\sqrt{(u_1 - u_2)^2 + (v_1 - v_2)^2}, as in Euclidean Distance. If uu is measured in grams and vv in kilograms, a change of 100 in uu adds 10000 to the squared distance, while a change of 1 in vv adds 1. The distance is then almost entirely a function of uu. Scaling makes both differences comparable.

Worked examples

Example
Tiny: five numbers, two scalings

The feature values are 2, 4, 6, 8, 10.

  1. Min-max. The minimum is 2 and the maximum is 10, so the range is 8. Scaled values are (x−2)/8(x - 2)/8, which gives 0, 0.25, 0.5, 0.75, 1. Interpretation: the smallest value maps to 0 and the largest to 1, with the others evenly placed.
  2. Mean. The mean is (2+4+6+8+10)/5=6(2 + 4 + 6 + 8 + 10)/5 = 6.
  3. Deviations. Subtract the mean from each value: −4,−2,0,2,4-4, -2, 0, 2, 4. Their sum is 0, as it must be.
  4. Variance. Square the deviations: 16, 4, 0, 4, 16, sum 40. Divide by 5 to get 8. The standard deviation is 8≈2.828\sqrt{8} \approx 2.828.
  5. Standardize. Divide each deviation by 2.828: about −1.414,−0.707,0,0.707,1.414-1.414, -0.707, 0, 0.707, 1.414. Interpretation: the middle value is exactly the mean, and the outer values are about 1.4 standard deviations away.
Example
Standard: why distance needs scaling

Three people are described by height in centimetres and income in dollars: A is (160, 30000), B is (180, 90000), and C is (170, 40000). We compare A and C.

  1. Raw differences. Height differs by 10 and income by 10000.
  2. Raw distance. 102+100002=100+100000000≈10000.005\sqrt{10^2 + 10000^2} = \sqrt{100 + 100000000} \approx 10000.005. The height difference contributes almost nothing.
  3. Scale. Use min-max on the three people. Height ranges from 160 to 180, so the range is 20; income ranges from 30000 to 90000, so the range is 60000. A maps to (0, 0), C maps to (10/20,10000/60000)=(0.5,0.1667)(10/20, 10000/60000) = (0.5, 0.1667).
  4. Scaled distance. 0.52+0.16672=0.25+0.0278≈0.527\sqrt{0.5^2 + 0.1667^2} = \sqrt{0.25 + 0.0278} \approx 0.527.
  5. Interpretation. Unscaled, the distance is a pure income measurement. Scaled, height adds 0.25 to the squared distance and income adds about 0.028. Both features now take part in the comparison, though the scaled ranges still decide how much each one counts.
Example
Realistic: house sizes and bedrooms

A training set has floor area between 80 and 200 square metres and bedroom count between 1 and 5. A new house has 150 square metres and 4 bedrooms. Use min-max scaling with the training ranges.

  1. Area. Subtract 80 from 150 to get 70, then divide by the range 120. Scaled area is 70/12070/120.
  2. Bedrooms. Subtract 1 from 4 to get 3, then divide by the range 4. Scaled bedrooms is 3/43/4.
  3. Interpretation. Both features are now between 0 and 1, so one unit change in either corresponds to a comparable step in the scaled space.
  4. Out-of-range check. A house of 220 square metres would scale to (220−80)/120=140/120(220 - 80)/120 = 140/120, which is above 1. The model still accepts it.
  5. Try it: a house has 92 square metres and 2 bedrooms. Using the same training ranges, what are its two scaled values? Answer: area (92−80)/120=12/120=0.1(92 - 80)/120 = 12/120 = 0.1, and bedrooms (2−1)/4=0.25(2 - 1)/4 = 0.25.

Common mistakes and tradeoffs

It is tempting to think that scaling changes what a model can learn. In fact, for a linear model with no regularization, scaling changes only how fast training converges and how the weights look, not the predictions the model can make, because the same family of functions is reached. It matters more for distance-based methods and for gradient descent with a fixed learning rate, because those are sensitive to the size of each feature.

It is tempting to scale the whole dataset before splitting it into training and test sets. In fact this leaks information from the test set into the centre and spread. Fit the scaler on the training data only, then apply it to the test data, as step 5 of the walkthrough does.

It is tempting to think min-max scaling always gives a good result. In fact one extreme value can squeeze the rest of the data into a tiny interval near 0. Standardization, or a robust scaler that uses the median and quartiles, is often safer when outliers are present.

Use scaling when the model uses distances, dot products between features, or gradient steps on features with very different spreads, such as nearest-neighbour methods, support vector machines, k-means clustering and neural networks. Scaling is not needed for tree-based models, which split each feature on thresholds and are unaffected by monotone rescaling.

History

Standard deviation as a named quantity came out of 19th-century statistics; Karl Pearson introduced the term in 1894. Expressing a value as the number of standard deviations from the mean, which is the z-score, became a routine tool in statistics well before computers were used for modelling. Scaling for machine learning became common once gradient-based training and distance-based classifiers were in wide use, because practitioners kept finding that unscaled features slowed or misled them.

Batch normalization, introduced by Ioffe and Szegedy in 2015, applied the same centring and scaling inside deep networks, to each layer's activations within a mini-batch. It made deep networks much easier to train, and it is the reason the idea is often associated with neural networks today.

Recap

  • A feature's units can make one column dominate distances and gradients, even when it is not the most informative.
  • Min-max scaling maps the training minimum to 0 and the maximum to 1, using (x−xmin⁡)/(xmax⁡−xmin⁡)(x - x_{\min})/(x_{\max} - x_{\min}).
  • Standardization maps the training mean to 0 and standard deviation to 1, using (x−μ)/σ(x - \mu)/\sigma.
  • The centre and spread must be fitted on training data only, then reused on new data.
  • Next, read K-Nearest Neighbors to see distances at work, and batch normalization for scaling inside a network.

Check yourself

QuestionA feature has training values 5, 10, 15, 20. What is the min-max scaled value of 12?Show answer

The minimum is 5 and the maximum is 20, so the range is 15. Then (12−5)/15=7/15≈0.467(12 - 5)/15 = 7/15 \approx 0.467. The answer is between 0 and 1 because 12 lies inside the training range.

QuestionTwo features have ranges 0 to 1000 and 0 to 1. Why does Euclidean distance mostly reflect the first feature before scaling, and what does scaling change?Show answer

A difference of 100 in the first feature contributes 1002=10000100^2 = 10000 to the squared distance, while a difference of 1 in the second contributes at most 1. The first feature therefore dominates. Scaling both to a 0 to 1 range makes a full-range change in either feature contribute at most 1 to the squared distance, so both features can influence the result in proportion to their informativeness.

QuestionYou scale a dataset using the mean and standard deviation of all rows, then split it into training and test sets. Why is this a mistake?Show answer

The test rows helped set the mean and spread, so the test set's information has leaked into the training features. The model's reported test performance will then be optimistic. The fix is to compute the centre and spread on the training set only and apply them unchanged to the test set.

QuestionA model for predicting house prices uses floor area and bedroom count. It is trained with min-max scaling. A house larger than any training example arrives. What does its scaled area look like, and should you clip it?Show answer

Its scaled area is above 1, because the formula uses the training maximum as the top of the range and the new value is beyond it. Whether to clip depends on the task: clipping to 1 hides the fact that the house is unusually large, while leaving the value above 1 lets the model extrapolate, which may be unreliable. Many systems record a flag for out-of-range inputs so the prediction can be treated with caution.

Sources