Sub topic 10
Scaling features for stable training
This chapter assumes you can write the NumPy gradient descent loop for logistic regression from the previous chapter. It also assumes you know what a gradient and a learning rate are, and that you know how to split data into train and test sets. Here you will see why features on very different scales make gradient descent slow or unstable, how to standardize them correctly, and how scaling interacts with regularization and with coefficient interpretation.
The problem: one learning rate, many scales
Batch gradient descent updates every weight with the same learning rate lr. The gradient for weight j is the mean of (p - y) * x_j, so it is proportional to the size of feature j. Suppose one feature is age (about 20 to 70) and another is income in dollars (about 20,000 to 150,000). The income gradient is roughly a thousand times larger than the age gradient.
Two things go wrong:
- A learning rate small enough to keep the income weight stable makes the age weight crawl.
- A learning rate that suits age makes the income weight overshoot, flip sign, and diverge.
Geometrically, the log loss surface has long, narrow valleys. Steps bounce across the narrow direction and make little progress along the long one.
Why it happens: curvature and conditioning
The Hessian (matrix of second derivatives) of the mean log loss is:
H = Xᵀ S X / n, where S = diag(pᵢ(1 − pᵢ))
Each pᵢ(1 − pᵢ) is at most 1/4. So the largest curvature is bounded by λ_max(XᵀX) / (4n), where λ_max is the largest eigenvalue. Gradient descent is only guaranteed to be stable when lr is below 2 divided by that curvature. A feature with huge values inflates λ_max, which forces a tiny learning rate.
The speed of convergence depends on the condition number, the ratio of the largest to the smallest eigenvalue of H. Unscaled features push this ratio very high. Standardizing the columns makes the diagonal of XᵀX / n equal to 1, which brings the eigenvalues much closer together. It does not remove correlation between features, but it removes the scale mismatch.
Standardization
Standardization (z-scoring) rescales each column to mean 0 and standard deviation 1:
x' = (x − μ) / σ
Here μ and σ are computed per column. Centering also helps the intercept: when every feature has mean zero, the intercept equals the log-odds at the average example, so starting b = 0 is a sensible guess.
Seeing the effect in NumPy
The script below builds two features on very different scales, trains the same gradient descent on raw and standardized versions, and compares the final loss. It reuses the update rule from the previous chapter and adds a loss function.
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-np.clip(z, -500, 500)))
def log_loss(X, y, w, b):
p = np.clip(sigmoid(X @ w + b), 1e-12, 1 - 1e-12)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
def fit_logistic(X, y, lr, steps):
n, d = X.shape
w, b = np.zeros(d), 0.0
for _ in range(steps):
error = sigmoid(X @ w + b) - y
w -= lr * (X.T @ error) / n
b -= lr * error.mean()
return w, b
rng = np.random.default_rng(0)
n = 500
age = rng.normal(40, 10, n)
income = rng.normal(50_000, 15_000, n)
X = np.column_stack([age, income])
true_z = 0.08 * (age - 40) + 0.00008 * (income - 50_000)
y = (rng.random(n) < sigmoid(true_z)).astype(float)
# Fit scaling statistics on the training data only.
mu, sigma = X.mean(axis=0), X.std(axis=0)
X_scaled = (X - mu) / sigma
w_raw, b_raw = fit_logistic(X, y, lr=1e-3, steps=2000)
w_std, b_std = fit_logistic(X_scaled, y, lr=0.1, steps=2000)
print("raw loss: ", log_loss(X, y, w_raw, b_raw))
print("scaled loss:", log_loss(X_scaled, y, w_std, b_std))The raw run uses a small learning rate because a larger one diverges on the income column. Even so, the age weight and the intercept barely move in 2000 steps, so its loss stays above the scaled run. The scaled run tolerates lr=0.1 and approaches the optimum quickly. Try lr=1e-3 on the scaled data, or lr=0.1 on the raw data, to see both failure modes.
Getting coefficients back to original units
A model trained on standardized features has coefficients per standard deviation. To express them per original unit, divide by the column's standard deviation and adjust the intercept:
w_orig = w_std / sigma
b_orig = b_std - np.sum(w_std * mu / sigma)
# Both parameterizations give the same scores.
print(np.allclose(X_scaled @ w_std + b_std, X @ w_orig + b_orig))This prints True. The two models are the same function written in different units. Odds ratios change meaning accordingly: exp(w_std[j]) is the odds multiplier per one standard deviation, and exp(w_orig[j]) is the multiplier per one raw unit.
Which scaler to use
| Scaler | Formula | Use when | Watch out for |
|---|---|---|---|
| `StandardScaler` | (x − μ) / σ | Default for logistic regression | Outliers inflate σ and shrink the typical spread |
| `MinMaxScaler` | (x − min) / (max − min) | You need a bounded range | One extreme value squeezes everything else |
| `RobustScaler` | (x − median) / IQR | Heavy outliers | Features are not unit variance, so regularization treats them unevenly |
Scaling and regularization
Scaling is not only an optimization convenience once you add an L2 or L1 penalty. The penalty applies to the size of each coefficient. A feature measured in dollars needs a tiny coefficient, so it is barely penalized. The same feature measured in thousands of dollars needs a coefficient 1000 times larger and is penalized heavily. Without scaling, the penalty favors features by their units. Standardizing puts all features on the same footing, so C in scikit-learn means the same thing for each of them. Scikit-learn does not penalize the intercept.
Avoiding leakage
Compute μ and σ from the training split only, then apply those same numbers to validation and test data. Fitting the scaler on the full dataset lets test-set information influence training. The effect is usually small, but it is a leak, and it grows under cross-validation. A scikit-learn Pipeline handles this automatically, because fit runs the scaler on the training fold only:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
print(cross_val_score(pipe, X, y, cv=5, scoring="roc_auc").mean())Edge cases and gotchas
- Constant columns. A column with
σ = 0gives a division by zero in hand-written code.StandardScalerleaves its scale at 1. Drop such columns anyway. - One-hot columns. Scaling 0/1 indicators is harmless but makes their coefficients harder to read. Many practitioners leave them unscaled, but then the penalty treats them differently from the scaled columns.
- Sparse data. Centering destroys sparsity. Use
StandardScaler(with_mean=False)orMaxAbsScaler. - Solvers. The
lbfgssolver is more forgiving than plain gradient descent, but it still raises aConvergenceWarningon badly scaled data. Scaling is the first fix to try before raisingmax_iter. - Predictions are unchanged in the unregularized case. The fitted decision function is the same either way, because scaling is a linear reparameterization. Scaling changes the path and the cost of optimization, not the optimum. With a penalty, the optimum does change.
- Deployment. Save the fitted scaler with the model. Scoring new data with different statistics silently breaks the model.
Exercise
A model trained on standardized features gives a coefficient of 0.9 for income. Income has a training standard deviation of 15,000 dollars. What is the coefficient per raw dollar, and by what factor do the odds change for each extra 1,000 dollars?
Show answer
The coefficient per dollar is 0.9 / 15,000 = 0.00006. For 1,000 dollars the log-odds change by 0.06, so the odds are multiplied by exp(0.06), about 1.06.