TExcelTAD
Home › Math for Machine Learning › Math for ML Exercises

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 x=(1,2,6)\mathbf{x} = (1, 2, 6) onto the span of (1,0,1)(1, 0, 1) and (0,1,1)(0, 1, 1) (Orthogonal Projections), and confirm that the residual is orthogonal to both basis vectors.

python · try it yourself
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:

text
projection: [2. 3. 5.]
B^T (x - p): [0. 0.]
Solution
python · try it yourself
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 L(w)=1N∑nlog⁡(1+e−ynwTxn)L(\mathbf{w}) = \frac{1}{N}\sum_n\log(1 + e^{-y_n\mathbf{w}^T\mathbf{x}_n}), the gradient is −1N∑nyn σ(−ynwTxn) xn-\frac{1}{N}\sum_n y_n\,\sigma(-y_n\mathbf{w}^T\mathbf{x}_n)\,\mathbf{x}_n. Implement it and check it against a central difference (Checking Gradients Numerically).

python · try it yourself
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:

text
match: True
Solution
python · try it yourself
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 N(μ,Σ)\mathcal{N}(\boldsymbol{\mu}, \Sigma) with μ=(1,2)\boldsymbol{\mu} = (1, 2) and Σ=[4223]\Sigma = \begin{bmatrix} 4 & 2 \\ 2 & 3 \end{bmatrix} using only standard normal draws and a Cholesky factor.

python · try it yourself
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:

text
mean: [1. 2.]
cov: [[4.0, 2.0], [2.0, 3.0]]
Solution
python · try it yourself
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 f(x)=12xTAxf(\mathbf{x}) = \frac{1}{2}\mathbf{x}^TA\mathbf{x} with A=diag⁡(1,100)A = \operatorname{diag}(1, 100) from (1,1)(1, 1) for 100 steps with γ=0.009\gamma = 0.009, first without and then with momentum α=0.8\alpha = 0.8 (Step Size and Momentum).

python · try it yourself
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 ff.

text
no momentum: f = 8.20e-02
momentum:    f = 4.62e-06
Solution
python · try it yourself
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, θ=(ΦTΦ+λI)−1ΦTy\boldsymbol{\theta} = (\Phi^T\Phi + \lambda I)^{-1}\Phi^T\mathbf{y} (MAP Estimation and Regularization), and compare test errors for λ=0\lambda = 0 and λ=10−2\lambda = 10^{-2}.

python · try it yourself
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:

text
lambda=0.0: test MSE 0.0616
lambda=0.01: test MSE 0.0046
Solution
python · try it yourself
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).

python · try it yourself
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:

text
explained variance ratio: [0.905 0.087 0.008]
Solution
python · try it yourself
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 (0,1,5,6)(0, 1, 5, 6) and a 2-component mixture with π=(0.5,0.5)\pi = (0.5, 0.5), means (1,4)(1, 4) and variances (1,1)(1, 1), perform one E-step and one M-step for the means (The EM Algorithm).

python · try it yourself
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:

text
responsibilities for component 1: [9.994e-01 9.890e-01 6.000e-04 0.000e+00]
new means: [0.4987 5.474 ]
Solution
python · try it yourself
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 w\mathbf{w} (no bias, no regularizer) for the data below (Soft Margin and the Hinge Loss).

python · try it yourself
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:

text
margins: [ 1.5   0.5   1.5  -0.05]  loss: 0.3875  subgradient: [-0.075 -0.15 ]
Solution
python · try it yourself
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 x−p\mathbf{x} - \mathbf{p} orthogonal to both basis vectors?

  1. By coincidence
  2. Because the normal equations BT(x−Bλ)=0B^T(\mathbf{x} - B\boldsymbol{\lambda}) = \mathbf{0} say exactly that
  3. Because BB is orthogonal
  4. Because x\mathbf{x} is in the subspace

Which sampling formula produces N(μ,Σ)\mathcal{N}(\boldsymbol{\mu}, \Sigma) from standard normal z\mathbf{z}?

  1. μ+Σz\boldsymbol{\mu} + \Sigma\mathbf{z}
  2. μ+Lz\boldsymbol{\mu} + L\mathbf{z} with Σ=LLT\Sigma = LL^T
  3. Σ−1z\Sigma^{-1}\mathbf{z}
  4. μz\boldsymbol{\mu}\mathbf{z}

In the M-step of EM, each new mean is…

  1. the median of all points
  2. a responsibility-weighted average of the points
  3. the old mean plus the gradient
  4. the point with the largest responsibility