---
title: Machine learning lab
heading: "Three models in NumPy: ridge regression in its primal and dual forms, logistic regression by Newton's method checked against an exact answer, and a two-layer network whose backpropagated gradients are verified by central differences"
eyebrow: S14 · Lesson 50 · Machine learning lab
xp: 100
---

::: hook
The formulas of the last thirty lessons become trustworthy once you've coded them and checked them against something independent. In this lab you'll write three small pieces that sit underneath real machine-learning libraries: ridge regression both ways, which shows the kernel trick's dual form is the same answer; logistic regression trained by Newton's method, tested against a case with an exact solution; and backpropagation for a small network, tested the way every framework's gradients are tested, against finite differences.
:::

::: predict
## Your Newton's method for logistic regression, with no penalty (λ = 0), is run on data that a line separates perfectly. What happens?

- [ ] It converges to the separating line in one step
- [x] The weights keep growing each iteration and never settle
- [ ] It converges, but to a poor boundary
- [ ] The gradient is zero from the start

::: reveal
With separable data the likelihood keeps rising as the weights grow along the separating direction (lesson 16), so there's no finite optimum. The predicted probabilities saturate at 0 and 1, the Hessian's weights y(1 − y) shrink toward zero, and each Newton step gets larger until the arithmetic overflows. Any λ > 0 gives a finite answer, which is why the function takes a penalty.
:::
:::

::: nameit
## Task 1: ridge both ways

`ridge` solves $(X^TX + \lambda I)\mathbf{w} = X^T\mathbf{t}$, a D × D system. `ridge_dual` solves $(XX^T + \lambda I)\mathbf{a} = \mathbf{t}$, an N × N system, and $\mathbf{w} = X^T\mathbf{a}$ should be identical. The tests use 6 examples with 40 features, where the dual is the smaller problem.

## Task 2: logistic regression by Newton's method

Start from w = 0 and repeat $\mathbf{w} \leftarrow \mathbf{w} - H^{-1}\mathbf{g}$ with $\mathbf{g} = X^T(\mathbf{y} - \mathbf{t}) + \lambda\mathbf{w}$ and $H = X^TRX + \lambda I$, where R is diagonal with entries $y_n(1 - y_n)$. One test has an exact answer: with an intercept and a single binary feature, the fitted probability in each group equals that group's fraction of positives.

## Task 3: backpropagation

For $Z = \tanh(XW_1 + \mathbf{b}_1)$, $Y = ZW_2 + \mathbf{b}_2$ and $E = \frac{1}{2}\sum(Y - T)^2$, the backward pass is $\delta_Y = Y - T$, $\partial E/\partial W_2 = Z^T\delta_Y$, $\delta_A = (\delta_YW_2^T) \odot (1 - Z^2)$ and $\partial E/\partial W_1 = X^T\delta_A$, with the biases' gradients as column sums of the δ's. The tests compare every entry with a central difference.
:::

::: example
## What should task 1 give for the points (0, 1), (1, 3) and (2, 4), with a bias column and λ = 1 on both weights?

::: solution
1. **Normal equations.**
   $$X^TX + I = \begin{bmatrix}4 & 3 \\ 3 & 6\end{bmatrix}$$
   and $X^T\mathbf{t}$ = (8, 11).
2. **Solve.**
   $$\begin{aligned} \mathbf w &= (15/15,\ 20/15) \\ &= (1, 1.333) \end{aligned}$$
3. **Compare λ = 0.** With λ = 0 it's lesson 1's least-squares line, intercept 1.167 and slope 1.5: the penalty pulled the slope down and the intercept with it.

**Answer:** task 1 should give **w** = (1, 1.333), an intercept of 1 and a slope of 1.333.
:::
:::

::: example
## What should task 2 give when 2 of 8 examples are positive with the feature off and 6 of 8 with it on?

::: solution
1. **Match the group rates.** The fit must reproduce the group rates 0.25 and 0.75.
2. **Bias.**
   $$\begin{aligned} w_0 &= \ln(0.25/0.75) \\ &= -1.099 \end{aligned}$$
3. **Weight.** $w_0 + w_1$ = ln 3, giving
   $$\begin{aligned} w_1 &= \ln 9 \\ &= 2.197 \end{aligned}$$
   The feature multiplies the odds by 9.
4. **Convergence.** Newton's method from zero gets there to ten digits within about five iterations.

**Answer:** task 2 should give $w_0$ = −1.099 and $w_1$ = 2.197 (ln 9).
:::
:::

::: check
kind: python

## Step 1. Write `ridge` and `ridge_dual`: one answer from two linear systems.

```python starter
import numpy as np

def ridge(X, t, lam):
    # Primal ridge regression: return w solving (X^T X + lam I) w = X^T t.
    return np.zeros(X.shape[1])

def ridge_dual(X, t, lam):
    # Dual form: return a solving (X X^T + lam I) a = t. Then w = X^T a.
    return np.zeros(X.shape[0])

X = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])
t = np.array([1.0, 3.0, 4.0])
print(ridge(X, t, 1.0), X.T @ ridge_dual(X, t, 1.0))
```

```python solution
import numpy as np

def ridge(X, t, lam):
    return np.linalg.solve(X.T @ X + lam*np.eye(X.shape[1]), X.T @ t)

def ridge_dual(X, t, lam):
    return np.linalg.solve(X @ X.T + lam*np.eye(X.shape[0]), t)

X = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])
t = np.array([1.0, 3.0, 4.0])
print(ridge(X, t, 1.0), X.T @ ridge_dual(X, t, 1.0))
```

```python tests
X = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])
t = np.array([1.0, 3.0, 4.0])
w = ridge(X, t, 1.0)
assert np.allclose(w, [1.0, 4/3], atol=1e-12), f"For the points (0, 1), (1, 3), (2, 4) with λ = 1, w should be (1, 1.3333); got {w}."
w0 = ridge(X, t, 0.0)
assert np.allclose(w0, np.linalg.lstsq(X, t, rcond=None)[0], atol=1e-12), f"With λ = 0, ridge should match least squares (1.1667, 1.5); got {w0}."
rng = np.random.default_rng(7)
A = rng.standard_normal((6, 40))
b = rng.standard_normal(6)
for lam in (0.1, 1.0, 10.0):
    wp = ridge(A, b, lam)
    wd = A.T @ ridge_dual(A, b, lam)
    assert np.allclose(wp, wd, atol=1e-10), f"With 6 examples and 40 features, X^T a from the dual must equal the primal w (λ = {lam}); the largest difference is {np.max(np.abs(wp - wd)):.2e}."
norms = [np.linalg.norm(ridge(A, b, lam)) for lam in (0.01, 0.1, 1.0, 10.0)]
assert all(norms[i] > norms[i + 1] for i in range(3)), f"Larger λ should shrink the weights; the norms were {np.round(norms, 4)}."
```

::: right
Right. The primal and dual forms give the same weights, as lesson 32 said; with 6 examples and 40 features the dual solved a 6 × 6 system instead of a 40 × 40 one.
:::
:::

::: check
kind: python

## Step 2. Write `logistic_newton`: logistic regression by iteratively reweighted least squares.

```python starter
import numpy as np

def sigmoid(a):
    return 1/(1 + np.exp(-a))

def logistic_newton(X, t, lam=0.0, iters=25):
    # Fit logistic regression by Newton's method (IRLS), starting from w = 0.
    # Minimize the cross-entropy plus lam/2 |w|^2. Each step:
    #   y = sigmoid(X w); g = X^T (y - t) + lam w; H = X^T diag(y(1 - y)) X + lam I
    #   w <- w - H^{-1} g
    # Return the final w.
    return np.zeros(X.shape[1])

x = np.array([0]*8 + [1]*8, dtype=float)
t = np.array([1, 1, 0, 0, 0, 0, 0, 0] + [1, 1, 1, 1, 1, 1, 0, 0], dtype=float)
X = np.column_stack([np.ones_like(x), x])
print(logistic_newton(X, t))
```

```python solution
import numpy as np

def sigmoid(a):
    return 1/(1 + np.exp(-a))

def logistic_newton(X, t, lam=0.0, iters=25):
    w = np.zeros(X.shape[1])
    for _ in range(iters):
        y = sigmoid(X @ w)
        g = X.T @ (y - t) + lam*w
        H = X.T @ (X*(y*(1 - y))[:, None]) + lam*np.eye(X.shape[1])
        w = w - np.linalg.solve(H, g)
    return w

x = np.array([0]*8 + [1]*8, dtype=float)
t = np.array([1, 1, 0, 0, 0, 0, 0, 0] + [1, 1, 1, 1, 1, 1, 0, 0], dtype=float)
X = np.column_stack([np.ones_like(x), x])
print(logistic_newton(X, t))
```

```python tests
x = np.array([0]*8 + [1]*8, dtype=float)
t = np.array([1, 1, 0, 0, 0, 0, 0, 0] + [1, 1, 1, 1, 1, 1, 0, 0], dtype=float)
X = np.column_stack([np.ones_like(x), x])
w = logistic_newton(X, t)
assert np.allclose(w, [np.log(1/3), np.log(3) - np.log(1/3)], atol=1e-10), f"With rates 0.25 and 0.75 in the two groups, the exact fit is w0 = ln(1/3) = -1.0986, w1 = ln 9 = 2.1972; got {w}."
rng = np.random.default_rng(3)
Z = np.column_stack([np.ones(200), rng.standard_normal((200, 3))])
p = sigmoid(Z @ np.array([0.3, 1.0, -2.0, 0.5]))
tt = (rng.random(200) < p).astype(float)
for lam in (0.0, 1.0):
    v = logistic_newton(Z, tt, lam)
    g = Z.T @ (sigmoid(Z @ v) - tt) + lam*v
    assert np.max(np.abs(g)) < 1e-9, f"At the optimum the penalized gradient must vanish (λ = {lam}); its largest entry is {np.max(np.abs(g)):.2e}."
v0, v1 = logistic_newton(Z, tt, 0.0), logistic_newton(Z, tt, 1.0)
assert np.linalg.norm(v1) < np.linalg.norm(v0), "The penalty should shrink the weights."
```

::: right
Right. Newton's method lands on the exact maximum-likelihood weights within a few iterations, the gradient vanishes at the optimum, and the penalty shrinks the weights.
:::
:::

::: check
kind: python

## Step 3. Write `forward_backward`: a two-layer network and its gradients.

```python starter
import numpy as np

def forward_backward(W1, b1, W2, b2, X, T):
    # A network with tanh hidden units and linear outputs:
    #   Z = tanh(X W1 + b1), Y = Z W2 + b2, E = 0.5 * sum((Y - T)^2)
    # X is N x D, W1 is D x H, b1 has H entries, W2 is H x K, b2 has K entries.
    # Return E and the gradients (dW1, db1, dW2, db2) by backpropagation.
    return 0.0, np.zeros_like(W1), np.zeros_like(b1), np.zeros_like(W2), np.zeros_like(b2)

W1 = np.array([[0.5]]); b1 = np.zeros(1); W2 = np.array([[2.0]]); b2 = np.zeros(1)
print(forward_backward(W1, b1, W2, b2, np.array([[1.0]]), np.array([[0.5]])))
```

```python solution
import numpy as np

def forward_backward(W1, b1, W2, b2, X, T):
    Z = np.tanh(X @ W1 + b1)
    Y = Z @ W2 + b2
    E = 0.5*np.sum((Y - T)**2)
    dY = Y - T
    dW2 = Z.T @ dY
    db2 = dY.sum(axis=0)
    dA = (dY @ W2.T)*(1 - Z**2)
    dW1 = X.T @ dA
    db1 = dA.sum(axis=0)
    return E, dW1, db1, dW2, db2

W1 = np.array([[0.5]]); b1 = np.zeros(1); W2 = np.array([[2.0]]); b2 = np.zeros(1)
print(forward_backward(W1, b1, W2, b2, np.array([[1.0]]), np.array([[0.5]])))
```

```python tests
W1 = np.array([[0.5]]); b1 = np.zeros(1); W2 = np.array([[2.0]]); b2 = np.zeros(1)
E, dW1, db1, dW2, db2 = forward_backward(W1, b1, W2, b2, np.array([[1.0]]), np.array([[0.5]]))
assert abs(E - 0.0899873768) < 1e-9 and abs(dW2[0, 0] - 0.1960459554) < 1e-9 and abs(dW1[0, 0] - 0.6672762298) < 1e-9, f"Lesson 25's example gives E = 0.0900, dE/dw2 = 0.1960, dE/dw1 = 0.6673; got {E:.10f}, {dW2[0, 0]:.10f}, {dW1[0, 0]:.10f}."
rng = np.random.default_rng(11)
D, H, K, N = 3, 5, 2, 7
P = [rng.standard_normal((D, H)), rng.standard_normal(H), rng.standard_normal((H, K)), rng.standard_normal(K)]
X = rng.standard_normal((N, D)); T = rng.standard_normal((N, K))
E, *G = forward_backward(*P, X, T)
names = ["W1", "b1", "W2", "b2"]
for i in range(4):
    num = np.zeros_like(P[i])
    for idx in np.ndindex(P[i].shape):
        Q = [p.copy() for p in P]; Q[i][idx] += 1e-6; Ep = forward_backward(*Q, X, T)[0]
        Q[i][idx] -= 2e-6; Em = forward_backward(*Q, X, T)[0]
        num[idx] = (Ep - Em)/2e-6
    err = np.max(np.abs(num - G[i]))/max(1.0, np.max(np.abs(num)))
    assert err < 1e-6, f"The gradient for {names[i]} disagrees with central differences: relative error {err:.2e}."
```

::: right
Right. Your backward pass agrees with central differences to better than one part in a million for every weight and bias of a random network.
:::
:::

::: explain
## Why is comparing backpropagation against central differences such a reliable test?

::: model
The central difference estimates each derivative from the error function alone, with no knowledge of the network's structure, and its truncation error falls as the square of the step, so with a step of $10^{-6}$ it's accurate to roughly $10^{-10}$ relative, far better than the bugs it's meant to catch. A mistake in a backward pass, such as a missing activation derivative, a transposed matrix or a forgotten bias, typically changes some gradient entries by tens of percent. Checking every parameter on a small random network with random inputs exercises every code path, so agreement to one part in a million is strong evidence that the backward pass is right everywhere.
:::
:::

::: practice

::: check
given: S = 2 | 50; T = 1 | 40; l = 0.1 | 20
answer: T/(S + l)
tolerance: 0.5%

## One-weight ridge: Σx² = {S}, Σxt = {T}, λ = {l}?

::: misses
- [any] $\sum xt/(\sum x^2 + \lambda)$.
:::
:::

::: check
given: m = 1 | 3 | 7; N = 10 | 20
answer: ln(m/(N - m))
tolerance: 0.5%

## An intercept-only logistic model is fitted to {m} positives out of {N}. What's the maximum-likelihood intercept?

::: misses
- [any] The log-odds of the positive fraction.
:::
:::

::: check
given: u = -1 | 1.2; v = -2.5 | 2; t = -0.5 | 1; x = 0.5 | 1.5
answer: (v*tanh(u*x) - t)*v*(1 - tanh(u*x)^2)*x
tolerance: 0.5%

## Backprop: $w_1$ = {u}, $w_2$ = {v}, x = {x}, t = {t}?

::: misses
- [any] $(y - t)w_2(1 - z^2)x$.
:::
:::
:::
