Sub topic 1
Why Feature Scale Matters
Numeric features often come in very different units. An age is a number between 0 and 100. A yearly income can be a number between 0 and several million. Many machine learning algorithms treat these numbers as if they were directly comparable. When they are not, the algorithm quietly gives more weight to whichever feature has the bigger numbers.
This chapter explains how that happens in three places: distance calculations, gradient-based training, and regularization. It also shows what scaling does about it. The following chapters cover which models need scaling and how StandardScaler and MinMaxScaler work.
Prerequisites
This chapter assumes you have:
- Basic Python and NumPy skills, such as indexing arrays and computing a mean along an axis.
- Familiarity with the mean and standard deviation of a column of numbers.
- A basic idea of training and test sets in machine learning.
- Some experience with scikit-learn estimators, meaning you have called
fitandpredictbefore.
What "scale" means
The scale of a feature is the typical size and spread of its values. Two features can carry equally useful information and still have very different scales:
| Feature | Typical range | Unit |
|---|---|---|
| Age | 18 to 90 | years |
| Yearly income | 20,000 to 200,000 | currency units |
| Number of children | 0 to 5 | count |
| Fraction of credit used | 0.0 to 1.0 | ratio |
Nothing in the data says that a 1-unit change in income is as important as a 1-unit change in age. One extra year of age is a real difference between two people. One extra currency unit of income is almost nothing. A model that only sees the raw numbers cannot know this. It sees "1" in both cases.
The scale of a feature is a side effect of the unit chosen to record it. Measure a distance in meters or in kilometers and the information is the same, but the numbers differ by a factor of 1000. A good model should not give different answers because someone picked a different unit. Many models do, and scaling removes that dependence.
Problem 1: distances are dominated by large numbers
Algorithms such as k-nearest neighbors, k-means, and support vector machines with an RBF kernel are built on distances between rows. The usual choice is Euclidean distance, which adds up the squared differences of every feature:
distance = sqrt((age1 - age2)^2 + (income1 - income2)^2)
A difference of 35 years squares to 1,225. A difference of 1,000 in income squares to 1,000,000. The income term is about 800 times larger, so the age term barely changes the result.
Here are three people, with age and yearly income as the two features:
import numpy as np
# Rows: person A, person B, person C. Columns: age, yearly income.
X = np.array([[25.0, 50_000.0],
[60.0, 51_000.0],
[26.0, 80_000.0]])
def dist(u, v):
return np.sqrt(np.sum((u - v) ** 2))
print("raw A-B:", dist(X[0], X[1]))
print("raw A-C:", dist(X[0], X[2]))
# Standardize each column by hand: (x - mean) / std
Z = (X - X.mean(axis=0)) / X.std(axis=0)
print("scaled A-B:", dist(Z[0], Z[1]))
print("scaled A-C:", dist(Z[0], Z[2]))The raw distances are about 1000.6 for A to B and exactly 30000.0 for A to C. By raw distance, person B is far closer to A than person C is. But B is 35 years older than A, while C is only one year older.
After standardizing each column, both distances come out near 2.15. They are almost tied. Each of B and C differs from A mostly in one feature, and after scaling each of those differences counts about equally. The age gap of 35 years is no longer drowned out by a small difference in income.
The raw ranking was an artifact of units. If the income had been recorded in thousands, the ranking would have flipped. After scaling, the answer no longer depends on that choice.
Problem 2: gradient descent struggles on stretched problems
Linear regression, logistic regression, and neural networks are usually trained with some form of gradient descent. The algorithm repeatedly nudges each weight against the gradient of the loss. The gradient with respect to a weight is proportional to the feature values multiplied by that weight's error signal.
When one feature has values near 1000 and another has values near 1, the gradient for the first weight is hundreds of times larger than for the second. The loss surface becomes a long, narrow valley. A learning rate small enough to be stable along the steep direction makes progress along the shallow direction painfully slow. A learning rate good for the shallow direction makes the steep direction overshoot and blow up.
This example trains the same model on raw and standardized features, using the same code:
import numpy as np
rng = np.random.default_rng(0)
n = 200
x1 = rng.uniform(0, 1, n) # small-scale feature
x2 = rng.uniform(0, 1000, n) # large-scale feature
X = np.column_stack([x1, x2])
y = 3 * x1 + 0.002 * x2 + rng.normal(0, 0.1, n)
def gradient_descent(X, y, lr, steps=200):
A = np.column_stack([np.ones(len(X)), X]) # add a bias column
w = np.zeros(A.shape[1])
for _ in range(steps):
grad = 2 * A.T @ (A @ w - y) / len(y)
w -= lr * grad
return np.mean((A @ w - y) ** 2)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
with np.errstate(all="ignore"):
print("raw features, lr=0.01: ", gradient_descent(X, y, lr=0.01))
print("scaled features, lr=0.1: ", gradient_descent(Z, y, lr=0.1))The raw run prints inf or nan. The second feature's squared values are in the hundreds of thousands, so each update overshoots the minimum by a larger amount than the last, and the weights grow until they overflow. The scaled run prints a loss close to 0.01, which is the variance of the noise added to y. That is the best any model could do here.
Raw features would need a learning rate around a million times smaller to stay stable. At that rate, the weight for x1 would barely move in 200 steps. Scaling lets one reasonable learning rate work for every weight.
Some solvers are less affected. Ordinary least squares solved in closed form gives the same predictions with or without scaling. But scikit-learn's iterative solvers for logistic regression, SGD-based models, and neural networks all benefit. A common symptom is a ConvergenceWarning that goes away after scaling.
Problem 3: regularization penalizes features unevenly
Regularized models such as Ridge, Lasso, and logistic regression with its default L2 penalty add a term to the loss that punishes large coefficients. The penalty is applied to the coefficients as numbers, with no regard for the units of the features.
Changing the unit of a feature changes its coefficient in the opposite direction. If income is measured in thousands instead of single units, its coefficient becomes 1000 times larger for the same fitted effect. The penalty on that coefficient grows by a factor of 1,000,000, because penalties use squares. The model is now pushed to shrink the income coefficient much more than before, even though the information in the feature is the same.
So with unscaled data, the same alpha penalizes features differently depending on their units. Features measured in small units get large coefficients and are shrunk hard. Features measured in large units get tiny coefficients and are barely penalized. With every column on a comparable scale, a single penalty strength treats the features on roughly equal terms.
What scaling does
Scaling replaces each column with a transformed version of itself. The two common transformations are:
- Standardization subtracts the column mean and divides by the column standard deviation. The result has mean 0 and standard deviation 1.
- Min-max scaling subtracts the column minimum and divides by the range. The result lies between 0 and 1.
Both are linear changes applied separately to each column. The next chapters cover the formulas, the scikit-learn classes, and when to prefer one over the other. For now, the important points are:
- Scaling changes the unit of a column, not the order of its values. The largest value in a column is still the largest afterwards.
- Scaling a column does not change the shape of its distribution. A right-skewed feature stays right-skewed, just on a different axis.
- Scaling is computed from data. The mean, standard deviation, minimum, and maximum are statistics that must be learned from your training data and then reused. Getting this wrong causes data leakage, which is covered in a later chapter.
Scaling only matters for features that are numeric and continuous
Scaling applies to numeric columns whose magnitudes carry meaning. It does not apply to arbitrary columns:
- A category stored as integer codes (for example, 0 for "red", 1 for "green", 2 for "blue") has no meaningful magnitude. Scaling those codes does not make them meaningful. Such columns should be one-hot encoded instead.
- A one-hot column already holds only 0 and 1 values, which is a scale comparable to other scaled features. Scaling these columns is usually unnecessary.
- The target column
yis a separate question. Scaling the target is not needed for classification and is optional for regression.
A quick diagnostic
Before choosing any scaler, look at the scales in your data. Computing the spread of each column takes one line:
import numpy as np
X = np.array([[25.0, 50_000.0, 0.31],
[60.0, 51_000.0, 0.88],
[26.0, 80_000.0, 0.05],
[41.0, 62_000.0, 0.47]])
print("mean:", X.mean(axis=0))
print("std: ", X.std(axis=0))
print("min: ", X.min(axis=0))
print("max: ", X.max(axis=0))If the standard deviations differ by orders of magnitude, as they do here (about 13 for age, about 11,000 for income, and about 0.3 for the credit fraction), then a scale-sensitive model will be dominated by the income column. A ratio of 10 or more between the largest and smallest standard deviation is a good reason to scale. A ratio of 1000 is a clear one.
Common mistakes
- Treating scaling as a cosmetic step. For distance-based and gradient-based models it can change accuracy substantially, not just training speed.
- Scaling the whole dataset before splitting it into training and test sets. This leaks test-set statistics into preprocessing. A later chapter shows the correct approach.
- Assuming scaling fixes outliers or skew. It does not, and it can make the effect of outliers more visible.
- Scaling one-hot or integer-coded categorical columns without thinking about whether their numeric values mean anything.
- Forgetting to apply the same scaling at prediction time. A model trained on scaled features must receive scaled features later.
Exercise
A k-nearest-neighbors classifier uses two features: height in meters (values near 1.7, spread of about 0.1) and weight in grams (values near 70000, spread of about 15000). Which feature will mostly determine which neighbors are chosen, and why? What would happen to the neighbors if weight were recorded in kilograms instead?
Show answer
Weight in grams dominates. Euclidean distance sums squared differences, and typical weight differences (thousands) are tens of thousands of times larger than typical height differences (tenths), so the height term is negligible. Recording weight in kilograms (values near 70, spread near 15) would make the weight differences about 1000 times smaller, which gives height a bigger share of the distance and changes which points count as neighbors. That is the problem: the result depends on the unit. After standardizing both columns, the choice of unit no longer matters.
Exercise
You fit a Ridge regression on two unscaled features. Feature A is measured in dollars (values in the tens of thousands). Feature B is a ratio between 0 and 1. Both matter equally for the target. Which feature's coefficient will be larger, and which one does the penalty shrink more heavily? How does standardizing change this?
Show answer
Feature B's coefficient will be much larger, because a 1-unit change in a 0-to-1 ratio is a huge change while a 1-unit change in dollars is tiny. The squared-coefficient penalty therefore shrinks B heavily and barely touches A, even though both are equally useful. After standardizing, both columns have standard deviation 1, so their coefficients are on comparable scales and the same alpha treats them similarly.