Sub topic 10
Scaling features for stable training
This chapter assumes you know the sigmoid model, log loss, and the batch gradient descent update from the earlier chapters. It also assumes basic NumPy.
Why scale features
Gradient descent uses one learning rate for every weight. If one feature is measured in single digits and another in tens of thousands, the same step size cannot suit both.
Two problems follow:
- Elongated loss surface. The loss changes steeply along the large-valued feature's weight and slowly along the small-valued one. A learning rate small enough to stay stable for the large feature makes progress on the small feature very slow. A larger rate overshoots and oscillates.
- Saturated sigmoid. A large feature value makes the score
X @ w + bhuge after a single update. The sigmoid then returns values near 0 or 1, the gradient vanishes or flips sign, andnp.exp(-z)can overflow.
Scaling puts the features on a comparable range, so one learning rate works for all of them.
Standardization
Standardization rescales each feature to mean 0 and standard deviation 1:
x_scaled = (x - mean) / stdThe mean and standard deviation come from the training set only. Computing them on the full dataset leaks information from the test set into training.
Seeing the difference
The script below builds two features, age and income, whose scales differ by a factor of about 1,500. It trains the same model on raw and standardized inputs.
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-np.clip(z, -500, 500)))
def fit_logistic(X, y, lr=0.1, steps=500):
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
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))
rng = np.random.default_rng(0)
n = 200
age = rng.normal(40, 10, n)
income = rng.normal(50000, 15000, n)
logits = 1.5 * (age - 40) / 10 + 1.0 * (income - 50000) / 15000
y = (rng.random(n) < sigmoid(logits)).astype(int)
X = np.column_stack([age, income])
w_raw, b_raw = fit_logistic(X, y)
print("raw loss: ", log_loss(X, y, w_raw, b_raw))
mean, std = X.mean(axis=0), X.std(axis=0)
X_scaled = (X - mean) / std
w_s, b_s = fit_logistic(X_scaled, y)
print("scaled loss:", log_loss(X_scaled, y, w_s, b_s))With the same learning rate and step count, the raw run bounces between saturated predictions and ends with a much higher loss. The scaled run converges smoothly to a loss near the best this data allows.
Other reasons to scale
- Regularization. L2 and L1 penalties apply to all weights equally. An unscaled feature with a large range needs a tiny weight, so the penalty barely touches it. A small-range feature gets penalized heavily. Scaling makes the penalty fair.
- Coefficient comparison. On standardized features, each coefficient describes a one-standard-deviation change, so you can compare their sizes.
Exercise
You standardize with the mean and standard deviation of the test set because the test set has a different distribution. What goes wrong?
Show answer
The model was trained on features scaled with training statistics, so its weights assume that scaling. Using test statistics changes the meaning of every feature value, which shifts the scores and the predictions. It also uses test data to prepare inputs, so the evaluation is no longer a clean estimate. Always apply the training mean and standard deviation to the test set.