Math for ML Exercises
Time to practise the whole course. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Derive the formula on paper first, then translate it line by line. When a result looks wrong, print shapes and check a tiny case by hand.
| # | Exercise | Practises |
|---|---|---|
| 1 | Project onto a subspace | normal equations, orthogonality |
| 2 | Gradient of the logistic loss | vector calculus, gradient checking |
| 3 | Sample a correlated Gaussian | Cholesky, covariance |
| 4 | Gradient descent with momentum | optimization |
| 5 | Ridge regression | MAP estimation, regularization |
| 6 | PCA by SVD | decompositions, explained variance |
| 7 | One EM step | responsibilities, weighted means |
| 8 | Hinge-loss subgradient | SVMs |
Exercise 1: Project onto a subspace
Project onto the span of and (Orthogonal Projections), and confirm that the residual is orthogonal to both basis vectors.
import numpy as np
B = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
x = np.array([1.0, 2.0, 6.0])
lam = np.zeros(2) # TODO: solve (B^T B) lam = B^T x
p = B @ lam
print("projection:", np.round(p, 4))
print("B^T (x - p):", np.round(B.T @ (x - p), 10) + 0)projection: [0. 0. 0.]
B^T (x - p): [7. 8.]
Expected output when solved:
projection: [2. 3. 5.]
B^T (x - p): [0. 0.]Solution
import numpy as np
B = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
x = np.array([1.0, 2.0, 6.0])
lam = np.linalg.solve(B.T @ B, B.T @ x)
p = B @ lam
print("projection:", np.round(p, 4))
print("B^T (x - p):", np.round(B.T @ (x - p), 10) + 0)projection: [2. 3. 5.]
B^T (x - p): [0. 0.]
Exercise 2: Gradient of the logistic loss
For , the gradient is . Implement it and check it against a central difference (Checking Gradients Numerically).
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(30, 3)); y = np.sign(rng.normal(size=30)); w = rng.normal(size=3)
loss = lambda w: np.mean(np.log1p(np.exp(-y * (X @ w))))
sig = lambda z: 1 / (1 + np.exp(-z))
grad = np.zeros(3) # TODO: the formula above
num = np.array([(loss(w + 1e-6 * e) - loss(w - 1e-6 * e)) / 2e-6 for e in np.eye(3)])
print("match:", np.allclose(grad, num, atol=1e-8))match: False
Expected output when solved:
match: TrueSolution
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(30, 3)); y = np.sign(rng.normal(size=30)); w = rng.normal(size=3)
loss = lambda w: np.mean(np.log1p(np.exp(-y * (X @ w))))
sig = lambda z: 1 / (1 + np.exp(-z))
grad = -(X.T @ (y * sig(-y * (X @ w)))) / len(y)
num = np.array([(loss(w + 1e-6 * e) - loss(w - 1e-6 * e)) / 2e-6 for e in np.eye(3)])
print("match:", np.allclose(grad, num, atol=1e-8))match: True
Exercise 3: Sample a correlated Gaussian
Draw 100,000 samples from with and using only standard normal draws and a Cholesky factor.
import numpy as np
rng = np.random.default_rng(1)
mu = np.array([1.0, 2.0]); Sigma = np.array([[4.0, 2.0], [2.0, 3.0]])
Z = rng.normal(size=(100000, 2))
X = Z # TODO: mu + Z L^T with L = cholesky(Sigma)
print("mean:", np.round(X.mean(axis=0), 1))
print("cov:", np.round(np.cov(X.T), 1).tolist())mean: [ 0. -0.]
cov: [[1.0, -0.0], [-0.0, 1.0]]
Expected output when solved:
mean: [1. 2.]
cov: [[4.0, 2.0], [2.0, 3.0]]Solution
import numpy as np
rng = np.random.default_rng(1)
mu = np.array([1.0, 2.0]); Sigma = np.array([[4.0, 2.0], [2.0, 3.0]])
Z = rng.normal(size=(100000, 2))
X = mu + Z @ np.linalg.cholesky(Sigma).T
print("mean:", np.round(X.mean(axis=0), 1))
print("cov:", np.round(np.cov(X.T), 1).tolist())mean: [1. 2.]
cov: [[4.0, 2.0], [2.0, 3.0]]
Exercise 4: Gradient descent with momentum
Minimize with from for 100 steps with , first without and then with momentum (Step Size and Momentum).
import numpy as np
A = np.diag([1.0, 100.0])
def run(alpha):
x, v = np.array([1.0, 1.0]), np.zeros(2)
for _ in range(100):
v = -0.009 * (A @ x) # TODO: include alpha * v
x = x + v
return 0.5 * x @ A @ x
print(f"no momentum: f = {run(0.0):.2e}")
print(f"momentum: f = {run(0.8):.2e}")no momentum: f = 8.20e-02
momentum: f = 8.20e-02
Expected output when solved: momentum reaches a much smaller .
no momentum: f = 8.20e-02
momentum: f = 4.62e-06Solution
import numpy as np
A = np.diag([1.0, 100.0])
def run(alpha):
x, v = np.array([1.0, 1.0]), np.zeros(2)
for _ in range(100):
v = alpha * v - 0.009 * (A @ x)
x = x + v
return 0.5 * x @ A @ x
print(f"no momentum: f = {run(0.0):.2e}")
print(f"momentum: f = {run(0.8):.2e}")no momentum: f = 8.20e-02
momentum: f = 4.62e-06
Exercise 5: Ridge regression
Fit degree-9 polynomial features to 12 noisy points with ridge regression, (MAP Estimation and Regularization), and compare test errors for and .
import numpy as np
rng = np.random.default_rng(2)
x = np.linspace(-1, 1, 12); y = np.cos(3 * x) + 0.15 * rng.normal(size=12)
xt = np.linspace(-1, 1, 400); yt = np.cos(3 * xt)
Phi = lambda x: np.vander(x, 10, increasing=True)
def ridge(lam):
return np.linalg.lstsq(Phi(x), y, rcond=None)[0] # TODO: use lam (solve the ridge system)
for lam in (0.0, 1e-2):
print(f"lambda={lam}: test MSE {np.mean((Phi(xt) @ ridge(lam) - yt)**2):.4f}")lambda=0.0: test MSE 0.0616
lambda=0.01: test MSE 0.0616
Expected output when solved:
lambda=0.0: test MSE 0.0616
lambda=0.01: test MSE 0.0046Solution
import numpy as np
rng = np.random.default_rng(2)
x = np.linspace(-1, 1, 12); y = np.cos(3 * x) + 0.15 * rng.normal(size=12)
xt = np.linspace(-1, 1, 400); yt = np.cos(3 * xt)
Phi = lambda x: np.vander(x, 10, increasing=True)
def ridge(lam):
P = Phi(x)
return np.linalg.lstsq(P.T @ P + lam * np.eye(10), P.T @ y, rcond=None)[0]
for lam in (0.0, 1e-2):
print(f"lambda={lam}: test MSE {np.mean((Phi(xt) @ ridge(lam) - yt)**2):.4f}")lambda=0.0: test MSE 0.0616
lambda=0.01: test MSE 0.0046
Exercise 6: PCA by SVD
Compute the explained variance ratios of a centred dataset with the SVD (PCA in Practice).
import numpy as np
rng = np.random.default_rng(3)
X = rng.normal(size=(400, 3)) @ np.array([[3.0, 0, 0], [1.0, 1.0, 0], [0, 0.2, 0.3]])
Xc = X # TODO: centre the data
s = np.linalg.svd(Xc, compute_uv=False)
print("explained variance ratio:", np.round(s**2 / np.sum(s**2), 3))explained variance ratio: [0.905 0.087 0.008]
Expected output when solved:
explained variance ratio: [0.905 0.087 0.008]Solution
import numpy as np
rng = np.random.default_rng(3)
X = rng.normal(size=(400, 3)) @ np.array([[3.0, 0, 0], [1.0, 1.0, 0], [0, 0.2, 0.3]])
Xc = X - X.mean(axis=0)
s = np.linalg.svd(Xc, compute_uv=False)
print("explained variance ratio:", np.round(s**2 / np.sum(s**2), 3))explained variance ratio: [0.905 0.087 0.008]
Exercise 7: One EM step
For 1-D points and a 2-component mixture with , means and variances , perform one E-step and one M-step for the means (The EM Algorithm).
import numpy as np
x = np.array([0.0, 1.0, 5.0, 6.0])
pi, mu, var = np.array([0.5, 0.5]), np.array([1.0, 4.0]), np.array([1.0, 1.0])
p = pi * np.exp(-(x[:, None] - mu)**2 / (2 * var))
r = p # TODO: normalize each row to get responsibilities
mu_new = mu # TODO: responsibility-weighted means
print("responsibilities for component 1:", np.round(r[:, 0], 4))
print("new means:", np.round(mu_new, 4))responsibilities for component 1: [3.033e-01 5.000e-01 2.000e-04 0.000e+00]
new means: [1. 4.]
Expected output when solved:
responsibilities for component 1: [9.994e-01 9.890e-01 6.000e-04 0.000e+00]
new means: [0.4987 5.474 ]Solution
import numpy as np
x = np.array([0.0, 1.0, 5.0, 6.0])
pi, mu, var = np.array([0.5, 0.5]), np.array([1.0, 4.0]), np.array([1.0, 1.0])
p = pi * np.exp(-(x[:, None] - mu)**2 / (2 * var))
r = p / p.sum(axis=1, keepdims=True)
mu_new = (r * x[:, None]).sum(axis=0) / r.sum(axis=0)
print("responsibilities for component 1:", np.round(r[:, 0], 4))
print("new means:", np.round(mu_new, 4))responsibilities for component 1: [9.994e-01 9.890e-01 6.000e-04 0.000e+00]
new means: [0.4987 5.474 ]
Exercise 8: Hinge-loss subgradient
Compute the average hinge loss and its subgradient with respect to (no bias, no regularizer) for the data below (Soft Margin and the Hinge Loss).
import numpy as np
X = np.array([[2.0, 1.0], [0.5, 0.5], [-1.0, -2.0], [0.2, -0.1]])
y = np.array([1.0, 1.0, -1.0, -1.0])
w = np.array([0.5, 0.5])
m = y * (X @ w)
loss = np.mean(np.maximum(0, 1 - m))
grad = np.zeros(2) # TODO: average of -y_n x_n over points with m < 1
print("margins:", m, " loss:", round(loss, 4), " subgradient:", np.round(grad, 4))margins: [ 1.5 0.5 1.5 -0.05] loss: 0.3875 subgradient: [0. 0.]
Expected output when solved:
margins: [ 1.5 0.5 1.5 -0.05] loss: 0.3875 subgradient: [-0.075 -0.15 ]Solution
import numpy as np
X = np.array([[2.0, 1.0], [0.5, 0.5], [-1.0, -2.0], [0.2, -0.1]])
y = np.array([1.0, 1.0, -1.0, -1.0])
w = np.array([0.5, 0.5])
m = y * (X @ w)
loss = np.mean(np.maximum(0, 1 - m))
active = m < 1
grad = -(y[active, None] * X[active]).sum(axis=0) / len(y)
print("margins:", m, " loss:", round(loss, 4), " subgradient:", np.round(grad, 4))margins: [ 1.5 0.5 1.5 -0.05] loss: 0.3875 subgradient: [-0.075 -0.15 ]
Test yourself
In Exercise 1, why is the residual orthogonal to both basis vectors?
- By coincidence
- Because the normal equations say exactly that
- Because is orthogonal
- Because is in the subspace
Which sampling formula produces from standard normal ?
- with
In the M-step of EM, each new mean is…
- the median of all points
- a responsibility-weighted average of the points
- the old mean plus the gradient
- the point with the largest responsibility