Sub topic 8
Minimizing the loss with gradient descent
This chapter assumes you know basic Python and NumPy, what a derivative and a gradient are, and what a loss function is. It also assumes you have seen log loss, the training objective for logistic regression. Here we treat gradient descent as a general tool and see how it behaves on that loss. The next chapter derives the exact gradient formula and implements it.
Why we need an iterative method
Linear regression has a closed-form solution. You solve the normal equations and get the best weights in one step. Logistic regression does not. The loss contains the sigmoid, so setting the gradient to zero gives equations with no algebraic solution.
We therefore search for good weights step by step. Gradient descent is the standard way to do this.
The core idea
The gradient of a loss is a vector. It has one entry per parameter. Each entry says how fast the loss grows if you increase that parameter a little. The gradient points uphill, in the direction where the loss rises fastest. To reduce the loss, step the opposite way.
Write all parameters as a vector θ (the weights and the bias) and the average log loss as J(θ). The update rule is:
θ ← θ − η ∇J(θ)
The symbol η (eta) is the learning rate. It sets the step size. Repeat the update until the loss stops improving.
A one-dimensional picture
Imagine a model with one parameter w. The loss J(w) is a curve. At any point the slope tells you which way is downhill. If the slope is positive, decrease w. If it is negative, increase w. Near the minimum the slope shrinks toward zero, so the steps shrink too. That is why gradient descent settles down without any special stopping trick.
The same logic holds in many dimensions. The gradient combines the slopes for every parameter, and one update moves all parameters at once.
Why the log loss is friendly
The average log loss for logistic regression is convex. A convex function has a bowl shape. It has no separate local minima that can trap the search. Any minimum you reach is a global minimum. This is a major reason logistic regression is so dependable. Neural networks do not offer this guarantee.
Convexity guarantees the minimum is not a trap. It does not guarantee fast convergence. A badly chosen learning rate or badly scaled features can still make training slow or unstable.
The learning rate
The learning rate is the most important setting in gradient descent.
| Learning rate | What happens |
|---|---|
| Too small | The loss falls, but very slowly. You may run out of steps first. |
| About right | The loss falls quickly and flattens near the minimum. |
| Too large | Steps overshoot the minimum. The loss bounces, or grows without bound. |
A practical way to choose is to try values spaced by factors of about 3 or 10, such as 0.001, 0.01, 0.1, and 1. Plot the loss against the step number for each. The best value is usually the largest one whose curve still decreases smoothly.
Watching it run
The following example minimizes the average log loss on a small synthetic data set. It records the loss at each step so you can see convergence. It computes the gradient with the formula Xᵀ(p − y)/n, which the next chapter derives.
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def log_loss(y, p, eps=1e-12):
p = np.clip(p, eps, 1 - eps)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
def descend(X, y, lr, steps):
n, d = X.shape
w = np.zeros(d)
b = 0.0
history = []
for _ in range(steps):
p = sigmoid(X @ w + b)
history.append(log_loss(y, p))
error = p - y
w -= lr * (X.T @ error) / n
b -= lr * error.mean()
return w, b, history
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(-1, 1, (100, 2)), rng.normal(1, 1, (100, 2))])
y = np.array([0] * 100 + [1] * 100)
for lr in [0.01, 0.1, 1.0]:
w, b, history = descend(X, y, lr, steps=200)
print(f"lr={lr}: start={history[0]:.4f} end={history[-1]:.4f}")The loss starts at about 0.693, which is log 2. With all weights at zero, every predicted probability is 0.5, and that is the loss of a coin flip. With the smallest rate the loss drops only a little in 200 steps. The larger rates get much closer to the minimum.
Initialization
We start at zero here. For logistic regression this is safe. The loss is convex, so the starting point does not change where you end up. It only changes how long the trip takes. In neural networks, all-zero starts cause problems, because identical units never become different. A single linear layer like this one does not have that issue.
Stopping rules
You need a rule for when to stop. Common choices:
- A fixed number of steps. This is simple, but you must check that it was enough.
- A tolerance on the loss. Stop when the improvement between steps falls below a small value, such as 1e-6.
- A tolerance on the gradient. Stop when the gradient norm is near zero, since a minimum has zero gradient.
Many implementations combine a step cap with a tolerance. scikit-learn's max_iter is such a cap. If the solver hits it before meeting the tolerance, you get a ConvergenceWarning. Treat that warning as a real signal that the model is not fully trained.
Batch, stochastic, and mini-batch variants
The code above computes the gradient over all n examples before each update. This is batch gradient descent. Each step is exact but costs a full pass over the data.
Two common variants trade accuracy of the gradient for speed:
- Stochastic gradient descent (SGD) uses one example per update. Updates are cheap and noisy.
- Mini-batch gradient descent uses a small group, such as 32 or 256 examples. It balances noise and cost, and it suits hardware that works well on arrays.
The noise in SGD means the loss does not fall smoothly. It jitters around the minimum. A decaying learning rate reduces that jitter over time. For small and medium tabular data sets, batch methods are fine. SGD matters when the data is too large to process in one pass.
Why feature scaling matters
Gradient descent is sensitive to feature scale. Suppose one feature is measured in the range 0 to 1 and another in the range 0 to 100000. The loss surface becomes a long, narrow valley. One learning rate cannot suit both directions. A rate small enough for the large feature crawls along the small one. A rate large enough for the small feature blows up along the large one.
Standardizing each feature to mean 0 and standard deviation 1 makes the valley rounder, and convergence becomes faster and steadier. The scaling chapter covers this in detail.
Common errors
- Forgetting the division by n. Without it, the step size grows with the data set size, and a rate that worked on 100 rows fails on 10000.
- Updating the bias with the wrong sign or skipping it. The bias needs its own gradient, the mean of (p − y).
- Computing
np.exp(-z)for very negative z. This overflows and produces warnings. Production code uses a numerically stable sigmoid, such asscipy.special.expit. - Taking
log(0)in the loss. Clip probabilities away from 0 and 1, as the example does. - Judging convergence by accuracy. Accuracy can stay flat while the loss still improves, and the reverse also happens.
Beyond plain gradient descent
scikit-learn does not use plain gradient descent for LogisticRegression by default. Its default solver, lbfgs, is a quasi-Newton method. It uses the history of recent gradients to estimate curvature, so it picks step sizes automatically and usually needs far fewer iterations. Other solvers include liblinear, newton-cg, saga, and sag. They differ in which penalties they support and in how they scale to large data. Plain gradient descent remains worth learning because every one of these methods is a refinement of the same idea: follow the loss downhill.
Exercise
You train with a learning rate of 5 and the loss grows larger at every step until it becomes nan. Features are already standardized. What is the most likely cause, and what is your first fix?
Show answer
The learning rate is too large, so each step overshoots the minimum and the error grows. Lower the rate, for example to 0.5 or 0.1, and plot the loss curve to confirm it now decreases smoothly. If it still diverges, check the gradient's sign and the division by n.
Exercise
With all weights and the bias set to zero, what is the average log loss on any data set with labels 0 and 1, and why?
Show answer
It is log 2, about 0.693. Every predicted probability is sigmoid(0) = 0.5, so each example contributes −log(0.5) regardless of its label.