Optimization and Regularization
A fitted model needs a rule for choosing its parameters. Optimization finds parameters that minimize an objective, such as prediction error. Regularization adds a penalty to that objective and changes which solution is preferred.
Read calculus and linear algebra first. This example fits invented response measurements against a standardized dose variable.
Define the objective
Section titled “Define the objective”The prediction is a + b*x, with intercept a and slope b. The mean squared error is the average of (prediction-observation)**2. Squaring removes the sign and places more weight on larger errors.
import numpy as np
dose = np.array([-2.0, -1.0, 0.0, 1.0, 2.0])response = np.array([0.8, 2.9, 5.2, 6.8, 9.3])design = np.column_stack([np.ones(dose.size), dose])coefficients = np.zeros(2)learning_rate = 0.1initial_residual = design @ coefficients - responseinitial_gradient = 2.0 * design.T @ initial_residual / dose.sizefirst_update = coefficients - learning_rate * initial_gradientprint("Initial residuals:", initial_residual)print("Initial gradient:", np.round(initial_gradient, 4))print("Coefficients after one update:", np.round(first_update, 4))Initial residuals: [-0.8 -2.9 -5.2 -6.8 -9.3]Initial gradient: [-10. -8.36]Coefficients after one update: [1. 0.836]The initial coefficients predict zero for every observation. The residuals therefore equal the negative observed responses. The first gradient entry describes how the loss changes with the intercept; the second describes its change with the slope.
Subtracting the scaled gradient increases a coefficient when its gradient entry is negative. That sign indicates that a small increase in the coefficient decreases the loss locally. Both entries use the same current residuals, so this is one simultaneous parameter update.
The next block repeats that calculation, starting from the original zero coefficients. The residuals and gradient change as the predictions change.
losses = []for iteration in range(100): residual = design @ coefficients - response losses.append(np.mean(residual ** 2)) gradient = 2.0 * design.T @ residual / dose.size coefficients = coefficients - learning_rate * gradientprint("Gradient descent coefficients:", np.round(coefficients, 4))print(f"Initial loss: {losses[0]:.6f}")print(f"Final loss: {np.mean((design @ coefficients - response) ** 2):.6f}")Gradient descent coefficients: [5. 2.09]Initial loss: 33.764000Final loss: 0.027800The design matrix adds a column of ones for the intercept. Each iteration calculates the gradient and moves against it. The learning rate controls the step size.
Check against a direct solution
Section titled “Check against a direct solution”This quadratic objective is convex, and this design has independent columns. It therefore has a unique least squares solution. A linear least squares solver gives a reference without an iterative learning rate.
direct, _, _, _ = np.linalg.lstsq(design, response, rcond=None)print("Least squares coefficients:", np.round(direct, 4))print("Agreement:", np.allclose(coefficients, direct, atol=1e-7))assert np.allclose(coefficients, direct, atol=1e-7)Least squares coefficients: [5. 2.09]Agreement: TrueThe Hessian is a matrix of second derivatives. It describes how the gradient changes as the parameters move. For this objective, the Hessian is 2*design.T @ design / n.
Its largest eigenvalue describes the strongest curvature direction and determines the stability limit for a constant step on this quadratic. A step between zero and 2/largest_eigenvalue converges here.
hessian = 2.0 * design.T @ design / dose.sizelargest_eigenvalue = np.linalg.eigvalsh(hessian).max()print(f"Upper step bound for this quadratic: {2.0 / largest_eigenvalue:.3f}")Upper step bound for this quadratic: 0.500This bound belongs to the current scaled design. Rescaling the input changes the Hessian. More general objectives need other convergence checks and may have local minima.
Penalize the slope
Section titled “Penalize the slope”Ridge regression adds a squared coefficient penalty. Here the objective is mean(residual**2) + penalty*b**2. The intercept remains unpenalized.
Multiplying the derivative equation by the sample count gives the system (X.T @ X + n*penalty*P) @ beta = X.T @ y. The diagonal matrix P selects the penalized coefficients.
penalty_matrix = np.diag([0.0, 1.0])for penalty in [0.0, 0.1, 1.0, 10.0]: system = design.T @ design + dose.size * penalty * penalty_matrix ridge = np.linalg.solve(system, design.T @ response) print(f"Penalty {penalty:4.1f}: " f"intercept {ridge[0]:.4f}, slope {ridge[1]:.4f}")Penalty 0.0: intercept 5.0000, slope 2.0900Penalty 0.1: intercept 5.0000, slope 1.9905Penalty 1.0: intercept 5.0000, slope 1.3933Penalty 10.0: intercept 5.0000, slope 0.3483A larger penalty shrinks the slope toward zero. It trades fit to the observed data against coefficient size. Packages can scale the loss and penalty differently, so the same numerical penalty need not specify the same objective.
Lasso uses absolute coefficient values instead of squares. Its objective has corners at zero, and it can set coefficients exactly to zero. Ordinary derivatives alone do not describe those corners.
from pathlib import Path
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 3.8))axes[0].plot(losses)axes[0].set(xlabel="Iteration", ylabel="Mean squared error")axes[1].scatter(dose, response, label="Invented observations")axes[1].plot(dose, design @ coefficients, label="Least squares fit")axes[1].set(xlabel="Standardized dose", ylabel="Response")axes[1].legend()fig.tight_layout()Path("outputs").mkdir(exist_ok=True)fig.savefig("outputs/optimization_fit.png", dpi=160)plt.close(fig)
Optimization does not measure generalization
Section titled “Optimization does not measure generalization”A small training loss shows that the optimizer fits the chosen objective. It does not show that predictions work on new patients. Choose penalties through validation and keep preprocessing inside each training split.
Check your understanding
Section titled “Check your understanding”Why does increasing the number of iterations not necessarily repair a learning rate that is too large?
An oversized step can move past the region of smaller loss. Repeating that unstable update can increase the error or cause oscillation. Inspect the loss sequence and the gradient rather than assuming that more updates must improve the fit.
Further reading
Section titled “Further reading”-
Google gradient descent lesson
The lesson explains parameter updates, loss curves, and the effect of the learning rate. Compare those controls with the convergence trace here.
-
NumPy linear algebra reference
The reference distinguishes least-squares solutions, linear-system solutions, and matrix norms. These interfaces support the direct-fit and ridge comparisons.
The cross-validation guide covers that separation. Continue with graphs and recurrence relations.