Feature Scaling, Explained

After reading this you will know why k-means and gradient descent break when one feature is measured on a bigger scale, how standardization, min-max and robust scaling fix that, and how to read the difference off numbers you can check by hand.

What feature scaling does and one example that shows why

Feature scaling is a rescaling of each column of your data so that no single feature dominates just because it happens to be measured in larger units. Distance-based methods (k-means, k-nearest neighbors, SVMs with an RBF kernel) and gradient-based methods (anything trained by gradient descent) silently assume the features share a comparable range. When they do not, the algorithm answers a different question than the one you asked.

Here is the hook. Take two clean clusters in 2-D. Cluster A sits near (1, 0.5) and cluster B near (3, 0.7). The true grouping is left versus right along feature 1. Now stretch feature 2 by a factor of 1000, so those 0.5 and 0.7 values become 500 and 700. Run k-means with k = 2. The Euclidean distance is now dominated by feature 2, and k-means splits the data along that axis instead. The clusters it returns have almost nothing to do with the real structure.

Scale both features to comparable ranges first and the same algorithm recovers the true left-versus-right split. The algorithm did not change. Only the units did.

When scaling matters and when it does not

Scaling changes the answer for any method that compares features using a distance or a gradient in the raw coordinate space.

Needs scaling
k-means, k-nearest neighbors, SVMs, PCA, and any linear or neural model trained by gradient descent. All of these treat "one unit of feature 1" and "one unit of feature 2" as directly comparable.
Indifferent to scaling
Decision trees, random forests and gradient-boosted trees. They split one feature at a time at a threshold. A monotone rescaling (multiply by 1000, take a log) moves the threshold but never changes which points fall on each side, so the tree is identical.

Fit the scaler on the training set only, then apply the same shift and divisor to the validation and test sets. If you compute the mean and standard deviation over all the data before splitting, information from the test set leaks into training and your reported error is optimistic.

The three scalers and their formulas

Standardization centers each feature at zero and divides by its standard deviation:

z_i = \frac{x_i - \bar{x}}{\sigma}

Here x_i is one raw value, \bar{x} is the feature mean and \sigma is its standard deviation. The result has mean 0 and variance 1. A value one standard deviation above the mean becomes +1 regardless of the original units.

Min-max scaling maps the observed range onto [0, 1]:

x_i' = \frac{x_i - x_{\min}}{x_{\max} - x_{\min}}

The smallest value becomes 0, the largest becomes 1, everything else lands in between. This preserves the shape of the distribution but is sensitive to the extremes, because a single large outlier sets x_{\max}.

Robust scaling uses the median and the interquartile range (IQR), the gap between the 75th and 25th percentiles:

x_i'' = \frac{x_i - \text{median}(x)}{\text{IQR}(x)}

The median and IQR ignore the far tails, so a handful of outliers cannot move the center or blow up the divisor. That is the whole reason robust scaling exists.

A worked example on the demo data

Scaling six points by hand

Use the demo default: two clusters, feature 2 stretched by a ratio of 1000. Take feature 2 values from six points, three per cluster: 500, 520, 540, 680, 700, 720.

  1. Mean: \bar{x} = (500+520+540+680+700+720)/6 = 610.
  2. Variance: the squared deviations are 12100, 8100, 4900, 4900, 8100, 12100, summing to 50200. Divide by 6 to get 8366.7, so \sigma = 91.47.
  3. Standardized value for 500: (500 - 610)/91.47 = -1.203. For 720: (720 - 610)/91.47 = 1.203. The whole column now spans about [-1.2, 1.2].
  4. Min-max: x_{\min} = 500, x_{\max} = 720, range 220. The value 500 maps to 0, 720 maps to 1, and 610 maps to (610-500)/220 = 0.5.
  5. Robust: sorted, the median is (540+680)/2 = 610. The first quartile is near 520, the third near 700, so IQR \approx 180. The value 500 maps to (500-610)/180 = -0.611.

Now feature 1 (values near 1 and 3) and scaled feature 2 both live within a couple of units of each other. k-means can weigh them evenly.

The next chart shows the same six points before and after standardization. Raw feature 2 dwarfs feature 1; standardized, they are comparable.

Raw feature 2 sits near 600; standardized values (scaled by 10 here so they are visible on the same axis) center on zero and span about minus 1.2 to plus 1.2.

Why gradient descent zigzags on raw data

For linear regression the loss is a bowl. Its curvature is described by the Hessian, and how fast gradient descent converges depends on the condition number \kappa, the ratio of the largest to the smallest eigenvalue of that Hessian.

\kappa = \frac{\lambda_{\max}}{\lambda_{\min}}

When one feature has a scale 1000 times another, the bowl becomes a long thin valley. The eigenvalue along the stretched direction is roughly the square of the scale ratio times the eigenvalue along the other, so \kappa can reach the order of 10^6. Gradient descent with a fixed step size must keep the step small enough for the steep direction (the largest safe rate shrinks as 1/\lambda_{\max}), which leaves it crawling along the shallow direction. The path bounces back and forth across the valley.

The number of iterations to reach a fixed accuracy grows roughly in proportion to \kappa. Scale the features and the eigenvalues become nearly equal, so \kappa \approx 1, the contours are near-circles, and the descent runs almost straight to the minimum.

Iterations to reach a fixed tolerance climb almost linearly with the scale ratio: about 12 at ratio 1, roughly 748 at ratio 100, and near 7455 at ratio 1000.

Without JavaScript: picture two loss-contour maps side by side. At scale ratio 1 both are circles and the descent arrow points straight at the center in a handful of steps. As you raise the ratio toward 1000, the raw-side contours stretch into a long thin ellipse and the descent path zigzags across it, taking hundreds or thousands of steps, while the scaled side stays circular and fast.

Reading the two panels and the numbers

The demo reports two figures per panel: iterations to converge for gradient descent, and cluster accuracy for k-means. Read them as a pair.

Typical readings at scale ratio 1000, two clean clusters
MetricRaw panelScaled panel
k-means cluster accuracy0.520.99
Gradient descent iterations745512
Split axis found by k-meansfeature 2 onlytrue left/right

Cluster accuracy near 0.5 on the raw side is the signature of a two-way split that ignores the true labels: the algorithm is grouping by the dominant axis and getting the true grouping right only by chance. On the scaled side, accuracy near 0.99 means the recovered clusters match the true ones almost everywhere. For gradient descent, the ratio of iterations (about 7455 / 12 = 620) tracks the condition number, not the sample size.

Common mistakes

Scaling the target instead of, or alongside, the features by accident. Scale the inputs. If you also scale the target you must remember to undo it before reading predictions in original units.

Using min-max when the data has outliers. One extreme value sets x_{\max}, so the entire remaining range gets squashed into a narrow band near zero. Add a single point at feature 2 = 5000 to the demo and watch min-max collapse the real spread. Robust scaling keeps the median and IQR steady because it reads the middle of the sorted data, not the tail.

If you are unsure, standardization is a safe default for gradient descent and for k-means. Switch to robust scaling when you can see a few points sitting far from the rest, and check the scaler statistics: a divisor (sigma, range, or IQR) that jumps when you remove one point is a warning that that scaler is being pulled by an outlier.

Assuming scaling helps a tree model. It does not. Time spent scaling before a random forest is wasted, and it can make the model harder to interpret because splits no longer read in original units.

Related tools

Scaling changes distances, which is exactly what fails as dimensions grow: the Curse of Dimensionality demo shows nearest neighbors breaking down for a related reason. Once a model is trained, tune its decision boundary with the ROC & Threshold Explorer, split its error into bias and variance with the Bias-Variance Decomposition, and confirm your evaluation is honest with the Cross-Validation Visualizer, which is where you enforce the "fit the scaler on training data only" rule fold by fold.

Frequently asked questions

Do I need to scale features for a random forest?

No. Trees split one feature at a time at a threshold, so any monotone rescaling leaves every split decision unchanged. Scaling matters for k-means, k-nearest neighbors, SVMs, PCA and gradient-descent models.

Standardization or min-max, which should I pick?

Standardization (mean 0, variance 1) is the safer default and is not bounded, which suits gradient descent. Use min-max when you need values in [0, 1] and you trust that there are no extreme outliers. If there are outliers, prefer robust scaling.

Why does robust scaling use the IQR instead of the standard deviation?

The standard deviation squares every deviation, so one far point can dominate it. The IQR only depends on the 25th and 75th percentiles. Move a single tail point from 720 to 7200 and sigma jumps from about 91 to over 2400, while the IQR near 180 barely moves.

Does scaling change the k-means result if features already share a scale?

Almost not at all. When both features already span comparable ranges, the condition number is near 1 and Euclidean distance weights them evenly, so the recovered clusters and the iteration count are about the same before and after scaling.

How much does the scale ratio actually slow gradient descent?

Roughly linearly in the condition number, and for linear regression the condition number grows with the square of the scale ratio. In the demo, going from ratio 1 to ratio 1000 raises iterations to converge from about 12 to about 7455, a factor near 620.