Training Machine Learning Models
Training a model is minimizing a loss over its parameters. Which optimizer to use depends on the structure of that problem: convex or not, smooth or not, how many parameters, how many examples, and how accurate the answer must be. This lesson trains the same classifier with several methods from this course and compares them, then maps model families to the methods libraries actually use. The optimizers specific to deep networks are covered in Math for Deep Learning & LLMs.
One problem, many optimizers
L2-regularized logistic regression,
is smooth and strongly convex, so every method converges to the same unique solution, and only speed differs.
import numpy as np
from scipy.optimize import minimize
rng = np.random.default_rng(0)
n, d = 2000, 30
X = rng.normal(size=(n, d)) * np.linspace(0.2, 3, d) # features on different scales
w_true = rng.normal(size=d)
y = np.where(X @ w_true + rng.normal(size=n) > 0, 1.0, -1.0)
lam = 1e-3
def f(w):
z = -y * (X @ w)
return np.mean(np.logaddexp(0, z)) + 0.5 * lam * w @ w
def grad(w):
s = 1 / (1 + np.exp(y * (X @ w)))
return -(X.T @ (y * s)) / n + lam * w
def hess(w):
p = 1 / (1 + np.exp(-(X @ w)))
return (X.T * (p * (1 - p))) @ X / n + lam * np.eye(d)
w_star = minimize(f, np.zeros(d), jac=grad, hess=hess, method="trust-exact", options={"gtol": 1e-12}).x
f_star = f(w_star)
for method, extra in [("BFGS", {}), ("L-BFGS-B", {}), ("CG", {}), ("Newton-CG", {"hess": hess})]:
r = minimize(f, np.zeros(d), jac=grad, method=method, options={"maxiter": 5000}, **extra)
print(f"{method:9s}: {r.nit:4d} iterations, {r.nfev:4d} f-evals, gap {r.fun - f_star:.1e}")
w, L = np.zeros(d), np.linalg.norm(X, 2)**2 / (4 * n) + lam # gradient descent with step 1/L
for k in range(1, 5001):
w -= grad(w) / L
print(f"GD 1/L : 5000 iterations, gap {f(w) - f_star:.1e}")BFGS : 103 iterations, 104 f-evals, gap 5.3e-09
L-BFGS-B : 39 iterations, 41 f-evals, gap 2.4e-08
CG : 43 iterations, 119 f-evals, gap 9.4e-09
Newton-CG: 10 iterations, 11 f-evals, gap 4.4e-13
GD 1/L : 5000 iterations, gap 7.7e-09
Plain gradient descent needs 5000 iterations to reach the accuracy that L-BFGS reaches in about 40 and Newton-CG in 10, because the features have very different scales (a large condition number). Curvature-aware methods do not care.
Preconditioning by standardization
Rescaling each feature to unit variance is the cheapest preconditioner, and it makes even gradient descent competitive:
import numpy as np
rng = np.random.default_rng(0)
n, d = 2000, 30
X = rng.normal(size=(n, d)) * np.linspace(0.2, 3, d)
y = np.where(X @ rng.normal(size=d) + rng.normal(size=n) > 0, 1.0, -1.0)
lam = 1e-3
def run_gd(X, steps=500):
f = lambda w: np.mean(np.logaddexp(0, -y * (X @ w))) + 0.5 * lam * w @ w
grad = lambda w: -(X.T @ (y / (1 + np.exp(y * (X @ w))))) / n + lam * w
H0 = X.T @ X / (4 * n) + lam * np.eye(d)
L = np.linalg.eigvalsh(H0).max()
w = np.zeros(d)
for _ in range(steps):
w -= grad(w) / L
return np.linalg.norm(grad(w)), np.linalg.cond(H0)
Xs = (X - X.mean(axis=0)) / X.std(axis=0)
for name, M in [("raw features", X), ("standardized", Xs)]:
g, kappa = run_gd(M)
print(f"{name:13s}: condition number of the curvature bound {kappa:7.1f}, gradient norm after 500 steps {g:.1e}")raw features : condition number of the curvature bound 216.0, gradient norm after 500 steps 5.5e-03
standardized : condition number of the curvature bound 1.5, gradient norm after 500 steps 5.2e-05
Which optimizer libraries use
| Model | Problem type | Typical optimizer |
|---|---|---|
| linear regression | least squares | QR / SVD (direct), or CG for huge sparse data |
| ridge | strongly convex quadratic | Cholesky, CG, SAG |
| lasso, elastic net | smooth + L1 | coordinate descent, FISTA |
| logistic regression | smooth convex | L-BFGS, Newton-CG, SAGA (large ) |
| linear SVM | non-smooth convex | dual coordinate descent (liblinear), SMO |
| GLMs | smooth convex | IRLS = Newton's method |
| Gaussian process hyperparameters | smooth non-convex, small | L-BFGS-B with restarts |
| neural networks | non-convex, huge and | mini-batch SGD, Adam/AdamW |
| gradient-boosted trees | greedy, second-order | Newton steps per leaf (XGBoost) |
| hyperparameters | black box, expensive | random search, Bayesian optimization |
Training is not just optimization
The goal of training is good performance on new data, not the exact minimum of the training loss. That changes the priorities:
- Low-accuracy solutions are often enough; the statistical error () dwarfs the optimization error, which is why SGD's slow final convergence rarely matters.
- Early stopping acts as a regularizer.
- In over-parameterized networks, the optimizer's implicit bias (which of many minima it reaches) affects generalization.
In software
- scikit-learn exposes the optimizer as
solver=(LogisticRegressionoffers "lbfgs", "newton-cg", "newton-cholesky", "sag", "saga" and "liblinear";LassoandElasticNetalways use coordinate descent); statsmodels uses Newton/IRLS; PyTorch/JAX/TensorFlow provide SGD-family optimizers plusLBFGS.
Go further: Comparing Optimizers and Checking Them Against torch.optim runs the deep-learning optimizers through one interface, with practical defaults.
Exercises
Exercise 1: Why convex helps
Why do all methods in the first example reach the same solution?
Answer
The objective is strongly convex, so it has a unique minimizer and no other stationary points.
Solution
The logistic loss is convex and the term makes the sum -strongly convex. Every convergent method must end at the unique minimizer; only the path and the cost differ.
Exercise 2: Pick an optimizer
Logistic regression with 50 million examples and 1,000 sparse features, trained once a day. Full-batch L-BFGS or SAGA/SGD?
Answer
A stochastic method (SAGA or SGD), possibly followed by a few L-BFGS passes.
Solution
Each full gradient touches 50 million examples; stochastic methods make progress after every mini-batch. SAGA keeps a linear rate on this strongly convex finite sum. If high accuracy is needed, finishing with a few full-batch quasi-Newton steps is a common hybrid.
Exercise 3: Newton for logistic regression (code)
Implement Newton's method (5 iterations) for the first example's objective and compare with w_star.
Answer
Newton converges to w_star in a handful of iterations.
Solution
import numpy as np
rng = np.random.default_rng(0)
n, d = 2000, 30
X = rng.normal(size=(n, d)) * np.linspace(0.2, 3, d)
y = np.where(X @ rng.normal(size=d) + rng.normal(size=n) > 0, 1.0, -1.0); lam = 1e-3
grad = lambda w: -(X.T @ (y / (1 + np.exp(y * (X @ w))))) / n + lam * w
def hess(w):
p = 1 / (1 + np.exp(-(X @ w)))
return (X.T * (p * (1 - p))) @ X / n + lam * np.eye(d)
w = np.zeros(d)
for k in range(8):
w -= np.linalg.solve(hess(w), grad(w))
print(k + 1, f"{np.linalg.norm(grad(w)):.1e}")1 3.1e-01
2 1.3e-01
3 5.4e-02
4 2.1e-02
5 7.2e-03
6 1.5e-03
7 9.2e-05
8 3.5e-07
Each Newton step here costs one solve. The gradient norm shrinks by a modest factor per step at first, while the iterate is far from the solution and the quadratic model is rough, then quadratically in the last steps.
Test yourself
Why is plain gradient descent slow on unscaled features?
- The loss is non-convex
- Different feature scales give a large condition number
- Gradients are wrong
- It needs integer weights
Which optimizer does scikit-learn's Lasso use?
- Coordinate descent
- Adam
- The simplex method
- Nelder-Mead
Why is low optimization accuracy often acceptable in ML?
- Statistical error from finite data dominates
- Losses are always zero
- Solvers are exact anyway
- Accuracy is never measured