holehouse.org Blog Machine learning notes

07: Regularization

The problem of overfitting

Overfitting with linear regression

Overfitting with logistic regression

Addressing overfitting

Cost function optimization for regularization

minθ12m∑i=1m(hθ(x(i))−y(i))2+1000θ32+1000θ42
J(θ)=12m[∑i=1m(hθ(x(i))−y(i))2+λ∑j=1nθj2] The penalty runs over θ1, θ2, …, θn — by convention θ0 is not penalised.

Regularized linear regression

J(θ)=12m[∑i=1m(hθ(x(i))−y(i))2+λ∑j=1nθj2] minθJ(θ)
import numpy as np

def J(theta, X, y, lam):
    m = len(y)
    err = ((X @ theta - y) ** 2).sum()
    penalty = lam * (theta[1:] ** 2).sum()   # theta[1:] - theta0 is not penalised
    return (err + penalty) / (2 * m)

The regularized cost. The penalty slices from theta[1:], leaving θ0 out — matching the sum from j = 1.

Repeat { θ0≔θ0−α1m∑i=1m(hθ(x(i))−y(i))x0(i) θj≔θj−α1m∑i=1m(hθ(x(i))−y(i))xj(i) } j = 1, 2, 3, …, n. θ0 has its own line above because it is never penalised — on the original slide the 0 is struck through in this index.
θj≔θj−α[1m∑i=1m(hθ(x(i))−y(i))xj(i)+λmθj] j = 1, 2, 3, …, n. The bracketed term is the partial derivative of the regularised J(θ).
θj≔θj(1−αλm)−α1m∑i=1m(hθ(x(i))−y(i))xj(i)

Regularization with the normal equation

θ=(XTX+λ[000…010…001…⋮⋮⋮1])−1XTy e.g. if n = 2:[000010001] An [n+1 x n+1] matrix — the identity with the top-left entry set to 0, so that θ0 escapes the penalty.
X = np.array([[1, 2, 2],   # x2 is an exact copy of x1,
              [1, 3, 3],   # so X.T @ X is singular
              [1, 4, 4],
              [1, 5, 5]], dtype=float)
y = np.array([2, 3, 4, 5], dtype=float)

np.linalg.det(X.T @ X)   # 0.0 - not invertible

L = np.eye(3)
L[0, 0] = 0              # the modified identity from the equation above
theta = np.linalg.solve(X.T @ X + 1.0 * L, X.T @ y)
X @ theta                # [2.14, 3.05, 3.95, 4.86]  - a sensible fit anyway

Redundant features make XTX singular — exactly the non-invertibility case from chapter 04. Adding λ times the modified identity makes the system solvable again.

Regularization for logistic regression

J(θ)=−1m[∑i=1my(i)loghθ(x(i))+(1−y(i))log(1−hθ(x(i)))]

Advanced optimization of regularized linear regression

def cost_function(theta):

    jVal = [code to compute J(θ)];

    gradient[0] = [code to compute ∂∂θ0J(θ)];

    gradient[1] = [code to compute ∂∂θ1J(θ)];

    gradient[2] = [code to compute ∂∂θ2J(θ)];
    ⋮
    gradient[n] = [code to compute ∂∂θnJ(θ)];
def cost_function(theta):

    jVal = [code to compute J(θ)];
      J(θ)=−1m[∑i=1my(i)loghθ(x(i))+(1−y(i))log(1−hθ(x(i)))]+λ2m∑j=1nθj2

    gradient[0] = [code to compute ∂∂θ0J(θ)];
      1m∑i=1m(hθ(x(i))−y(i))x0(i)

    gradient[1] = [code to compute ∂∂θ1J(θ)];
      1m∑i=1m(hθ(x(i))−y(i))x1(i)+λmθ1

    gradient[2] = [code to compute ∂∂θ2J(θ)];
      1m∑i=1m(hθ(x(i))−y(i))x2(i)+λmθ2
    ⋮
    gradient[n] = [code to compute ∂∂θnJ(θ)];