Optimization 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: Test each piece on a tiny case you can solve by hand first. When an optimizer misbehaves, print the objective, the gradient norm and the constraint violation every few iterations.
| # | Exercise | Practises |
|---|---|---|
| 1 | Backtracking line search | Armijo condition, gradient descent |
| 2 | Newton's method | Hessians, quadratic convergence |
| 3 | The BFGS update | quasi-Newton, secant equation |
| 4 | Projection onto the simplex | projected gradient, KKT |
| 5 | A production LP with shadow prices | linear programming, duality |
| 6 | ISTA for the lasso | proximal methods, sparsity |
| 7 | SGD with a decaying step | stochastic optimization |
| 8 | Project selection | integer programming |
Exercise 1: Backtracking line search
Complete the Armijo backtracking loop (Line Search and Backtracking) and minimize from with steepest descent.
import numpy as np
f = lambda p: (p[0] - 1)**4 + (p[0] - 2 * p[1])**2
grad = lambda p: np.array([4 * (p[0] - 1)**3 + 2 * (p[0] - 2 * p[1]), -4 * (p[0] - 2 * p[1])])
x = np.array([0.0, 3.0])
for k in range(200):
g = grad(x)
t = 1.0
# TODO: while the Armijo condition f(x - t g) <= f(x) - 1e-4 t |g|^2 fails, halve t
x = x - 0.0 * t * g
print("x =", np.round(x, 3), " f =", round(f(x), 6))x = [0. 3.] f = 37.0
Expected output when solved:
x = [1.051 0.526] f = 7e-06Solution
import numpy as np
f = lambda p: (p[0] - 1)**4 + (p[0] - 2 * p[1])**2
grad = lambda p: np.array([4 * (p[0] - 1)**3 + 2 * (p[0] - 2 * p[1]), -4 * (p[0] - 2 * p[1])])
x = np.array([0.0, 3.0])
for k in range(200):
g = grad(x)
t = 1.0
while f(x - t * g) > f(x) - 1e-4 * t * (g @ g):
t *= 0.5
x = x - t * g
print("x =", np.round(x, 3), " f =", round(f(x), 6))x = [1.051 0.526] f = 7e-06
The minimum is at . The quartic term is very flat near , so steepest descent approaches slowly; 200 steps get close but not exact.
Exercise 2: Newton's method
Minimize with pure Newton steps from (Newton's Method). Fill in the Hessian.
import numpy as np
grad = lambda p: np.array([np.exp(p[0] + p[1]) + 2 * p[0], np.exp(p[0] + p[1]) + 4 * p[1]])
def hess(p):
return 10 * np.eye(2) # TODO: the true Hessian (this placeholder gives gradient steps)
x = np.array([1.0, 1.0])
for k in range(5):
x = x - np.linalg.solve(hess(x), grad(x))
print(k + 1, f"{np.linalg.norm(grad(x)):.1e}")1 1.1e+00
2 7.2e-01
3 5.1e-01
4 3.7e-01
5 2.8e-01
Expected output when solved: the gradient norm collapses quadratically.
1 4.9e+00
2 1.1e+00
3 6.9e-02
4 2.8e-04
5 4.4e-09Solution
import numpy as np
grad = lambda p: np.array([np.exp(p[0] + p[1]) + 2 * p[0], np.exp(p[0] + p[1]) + 4 * p[1]])
def hess(p):
e = np.exp(p[0] + p[1])
return np.array([[e + 2, e], [e, e + 4]])
x = np.array([1.0, 1.0])
for k in range(5):
x = x - np.linalg.solve(hess(x), grad(x))
print(k + 1, f"{np.linalg.norm(grad(x)):.1e}")1 4.9e+00
2 1.1e+00
3 6.9e-02
4 2.8e-04
5 4.4e-09
With the placeholder the update is a plain gradient step with step size 0.1, which converges only linearly.
Exercise 3: The BFGS update
Implement the inverse BFGS update and check the secant equation (Quasi-Newton Methods and BFGS).
import numpy as np
H = np.eye(3)
s = np.array([0.5, -0.2, 0.1]); y = np.array([1.0, -0.1, 0.4])
rho = 1 / (y @ s)
H_new = H # TODO: (I - rho s y^T) H (I - rho y s^T) + rho s s^T
print("secant equation holds:", np.allclose(H_new @ y, s))
print("symmetric:", np.allclose(H_new, H_new.T), " positive definite:", bool(np.all(np.linalg.eigvalsh(H_new) > 0)))secant equation holds: False
symmetric: True positive definite: True
Expected output when solved:
secant equation holds: True
symmetric: True positive definite: TrueSolution
import numpy as np
H = np.eye(3)
s = np.array([0.5, -0.2, 0.1]); y = np.array([1.0, -0.1, 0.4])
rho = 1 / (y @ s)
I = np.eye(3)
H_new = (I - rho * np.outer(s, y)) @ H @ (I - rho * np.outer(y, s)) + rho * np.outer(s, s)
print("secant equation holds:", np.allclose(H_new @ y, s))
print("symmetric:", np.allclose(H_new, H_new.T), " positive definite:", bool(np.all(np.linalg.eigvalsh(H_new) > 0)))secant equation holds: True
symmetric: True positive definite: True
Positive definiteness is preserved because .
Exercise 4: Projection onto the simplex
Finish the sort-based projection onto and use it in projected gradient descent to find the convex combination of three points closest to (Projected Gradient Descent).
import numpy as np
def project_simplex(z):
u = np.sort(z)[::-1]; css = np.cumsum(u)
k = np.nonzero(u * np.arange(1, len(z) + 1) > css - 1)[0][-1]
tau = 0.0 # TODO: (css[k] - 1) / (k + 1)
return np.maximum(z - tau, 0)
V = np.array([[0.0, 0.0], [3.0, 0.0], [0.0, 3.0]]).T # columns are the three points
p = np.array([2.0, 1.0])
w = np.ones(3) / 3
for _ in range(500):
w = project_simplex(w - 0.05 * V.T @ (V @ w - p))
print("weights:", np.round(w, 4), " sum:", round(float(w.sum()), 4), " point:", np.round(V @ w, 4))weights: [0.3333 0.6667 0.3333] sum: 1.3333 point: [2. 1.]
Expected output when solved:
weights: [0. 0.6667 0.3333] sum: 1.0 point: [2. 1.]Solution
import numpy as np
def project_simplex(z):
u = np.sort(z)[::-1]; css = np.cumsum(u)
k = np.nonzero(u * np.arange(1, len(z) + 1) > css - 1)[0][-1]
tau = (css[k] - 1) / (k + 1)
return np.maximum(z - tau, 0)
V = np.array([[0.0, 0.0], [3.0, 0.0], [0.0, 3.0]]).T
p = np.array([2.0, 1.0])
w = np.ones(3) / 3
for _ in range(500):
w = project_simplex(w - 0.05 * V.T @ (V @ w - p))
print("weights:", np.round(w, 4), " sum:", round(float(w.sum()), 4), " point:", np.round(V @ w, 4))weights: [0. 0.6667 0.3333] sum: 1.0 point: [2. 1.]
The point lies inside the triangle, so it is its own projection: reproduces it exactly. Without the "projection" only clips negatives and the weights do not sum to 1.
Exercise 5: A production LP with shadow prices
A bakery makes bread (profit 3 per batch) and cakes (profit 5). Bread needs 2 hours of oven time and 1 kg of flour per batch; cakes need 3 hours and 2 kg. There are 12 oven hours and 7 kg of flour. Solve the LP and report the shadow prices (Sensitivity and Shadow Prices).
import numpy as np
from scipy.optimize import linprog
profit = np.array([3.0, 5.0])
A = np.array([[2.0, 3.0], [1.0, 2.0]]); b = np.array([12.0, 7.0])
res = linprog(np.zeros(2), A_ub=A, b_ub=b, bounds=[(0, None)] * 2, method="highs") # TODO: maximize profit
print("plan:", np.round(res.x, 4) + 0, " profit:", round(float(profit @ res.x), 4))
print("shadow prices (oven, flour):", np.round(-res.ineqlin.marginals, 4) + 0)plan: [0. 0.] profit: 0.0
shadow prices (oven, flour): [0. 0.]
Expected output when solved:
plan: [3. 2.] profit: 19.0
shadow prices (oven, flour): [1. 1.]Solution
import numpy as np
from scipy.optimize import linprog
profit = np.array([3.0, 5.0])
A = np.array([[2.0, 3.0], [1.0, 2.0]]); b = np.array([12.0, 7.0])
res = linprog(-profit, A_ub=A, b_ub=b, bounds=[(0, None)] * 2, method="highs")
print("plan:", np.round(res.x, 4) + 0, " profit:", round(float(profit @ res.x), 4))
print("shadow prices (oven, flour):", np.round(-res.ineqlin.marginals, 4) + 0)plan: [3. 2.] profit: 19.0
shadow prices (oven, flour): [1. 1.]
Both resources are used up. One more oven hour is worth 1 and one more kilogram of flour 1 in extra profit, as long as the same plan structure stays optimal.
Exercise 6: ISTA for the lasso
Complete the soft-thresholding operator and run ISTA (The Lasso with ISTA and FISTA).
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(50, 10)); w_true = np.zeros(10); w_true[[1, 4, 7]] = [2.0, -3.0, 1.5]
y = X @ w_true + 0.1 * rng.normal(size=50)
lam = 5.0; L = np.linalg.norm(X, 2)**2
def soft(v, k):
return v # TODO: sign(v) * max(|v| - k, 0)
w = np.zeros(10)
for _ in range(2000):
w = soft(w - X.T @ (X @ w - y) / L, lam / L)
print("weights:", np.round(w, 3) + 0)
print("non-zeros:", int(np.sum(np.abs(w) > 1e-8)))weights: [ 0.01 1.988 0.012 0.004 -2.985 0. -0.012 1.509 0.011 0.003]
non-zeros: 10
Expected output when solved:
weights: [ 0. 1.886 0. 0. -2.856 0. 0. 1.384 0. 0. ]
non-zeros: 3Solution
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(50, 10)); w_true = np.zeros(10); w_true[[1, 4, 7]] = [2.0, -3.0, 1.5]
y = X @ w_true + 0.1 * rng.normal(size=50)
lam = 5.0; L = np.linalg.norm(X, 2)**2
def soft(v, k):
return np.sign(v) * np.maximum(np.abs(v) - k, 0)
w = np.zeros(10)
for _ in range(2000):
w = soft(w - X.T @ (X @ w - y) / L, lam / L)
print("weights:", np.round(w, 3) + 0)
print("non-zeros:", int(np.sum(np.abs(w) > 1e-8)))weights: [ 0. 1.886 0. 0. -2.856 0. 0. 1.384 0. 0. ]
non-zeros: 3
Without thresholding the iteration is plain gradient descent on least squares, and every weight is non-zero.
Exercise 7: SGD with a decaying step
Fit a least-squares line with SGD. A constant step leaves the iterate jittering; add the decaying step (Step Sizes and Convergence of SGD).
import numpy as np
rng = np.random.default_rng(1)
x = rng.uniform(-1, 1, 1000); y = 3 * x - 1 + 0.5 * rng.normal(size=1000)
X = np.column_stack([np.ones_like(x), x])
w_star = np.linalg.lstsq(X, y, rcond=None)[0]
w = np.zeros(2)
for k in range(20000):
i = rng.integers(1000)
t = 0.1 # TODO: decaying step
w -= t * X[i] * (X[i] @ w - y[i])
print("distance to the least-squares solution:", round(float(np.linalg.norm(w - w_star)), 4))distance to the least-squares solution: 0.0774
Expected output when solved: a much smaller distance.
distance to the least-squares solution: 0.0249Solution
import numpy as np
rng = np.random.default_rng(1)
x = rng.uniform(-1, 1, 1000); y = 3 * x - 1 + 0.5 * rng.normal(size=1000)
X = np.column_stack([np.ones_like(x), x])
w_star = np.linalg.lstsq(X, y, rcond=None)[0]
w = np.zeros(2)
for k in range(20000):
i = rng.integers(1000)
t = 0.1 / (1 + k / 500)
w -= t * X[i] * (X[i] @ w - y[i])
print("distance to the least-squares solution:", round(float(np.linalg.norm(w - w_star)), 4))distance to the least-squares solution: 0.0249
Exercise 8: Project selection
Choose projects to maximize value within a budget of 10, where project 3 requires project 1 (0-based indices) (Integer Programming). Add the dependency constraint .
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds
value = np.array([6.0, 5.0, 8.0, 9.0, 3.0]); cost = np.array([4.0, 3.0, 5.0, 4.0, 2.0])
A = np.array([cost]); lb = [-np.inf]; ub = [10.0]
# TODO: add a row for z3 - z1 <= 0
res = milp(-value, constraints=LinearConstraint(A, lb, ub), integrality=np.ones(5), bounds=Bounds(0, 1))
z = np.round(res.x).astype(int)
print("chosen:", np.nonzero(z)[0].tolist(), " value:", float(value @ z), " cost:", float(cost @ z))chosen: [0, 3, 4] value: 18.0 cost: 10.0
Expected output when solved:
chosen: [1, 3, 4] value: 17.0 cost: 9.0Solution
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds
value = np.array([6.0, 5.0, 8.0, 9.0, 3.0]); cost = np.array([4.0, 3.0, 5.0, 4.0, 2.0])
A = np.array([cost, [0, -1, 0, 1, 0]]); lb = [-np.inf, -np.inf]; ub = [10.0, 0.0]
res = milp(-value, constraints=LinearConstraint(A, lb, ub), integrality=np.ones(5), bounds=Bounds(0, 1))
z = np.round(res.x).astype(int)
print("chosen:", np.nonzero(z)[0].tolist(), " value:", float(value @ z), " cost:", float(cost @ z))chosen: [1, 3, 4] value: 17.0 cost: 9.0
The dependency forces project 1 into any plan with project 3, which changes the best choice.
Test yourself
Which method would you choose first for a smooth convex problem with 10 variables and cheap Hessians?
- Newton's method with a line search or trust region
- Simulated annealing
- Branch and bound
- SGD with a constant step
An LP solver reports shadow price 0 for a resource. This means…
- the resource has slack at the optimum
- the resource is the bottleneck
- the LP is infeasible
- the resource is free to buy
Soft thresholding in ISTA is the proximal operator of…
- the squared L2 norm
- the L1 norm
- the indicator of a box
- the hinge loss