TExcelTAD
Home › Optimization › Mini Project: A Small Optimization Toolkit

Mini Project: A Small Optimization Toolkit

In this project you build a small optimization toolkit from scratch and check every piece against SciPy. It has a line search, a BFGS minimizer, a projected-gradient solver for bound constraints, a branch-and-bound solver for small integer programs, and a logistic-regression trainer that uses the BFGS code. Every part comes from a chapter of the course.

What we are building:

Step Part Course topics
1. Line search and BFGS unconstrained solver Armijo condition, inverse-Hessian update
2. Bound constraints projected gradient projection, KKT conditions
3. An LP and its dual linear programming linprog, duality, shadow prices
4. Branch and bound integer programming LP relaxations, bounding, branching
5. Train a classifier application logistic loss, gradients, BFGS

Note: Each step is a complete program (the playground does not share variables between runs), so helper functions are repeated where a later step needs them.

Step 1: Line search and BFGS

The minimizer combines the inverse BFGS update (Quasi-Newton Methods and BFGS) with a backtracking line search (Line Search and Backtracking). It skips the update when the curvature yTs\mathbf{y}^T\mathbf{s} is not positive, which keeps HH positive definite. The test problem is the Rosenbrock function, whose curved valley is hard for gradient descent.

python · try it yourself
import numpy as np
from scipy.optimize import minimize

def backtrack(f, x, fx, g, d, t=1.0, c=1e-4):
    while f(x + t * d) > fx + c * t * (g @ d):
        t *= 0.5
    return t

def bfgs(f, grad, x0, tol=1e-8, max_iter=500):
    x = np.asarray(x0, float); n = len(x); H = np.eye(n); g = grad(x)
    for k in range(max_iter):
        if np.linalg.norm(g) < tol:
            return x, k
        d = -H @ g
        t = backtrack(f, x, f(x), g, d)
        s = t * d; x_new = x + s; g_new = grad(x_new); y = g_new - g
        if y @ s > 1e-12:
            rho = 1 / (y @ s); I = np.eye(n)
            H = (I - rho * np.outer(s, y)) @ H @ (I - rho * np.outer(y, s)) + rho * np.outer(s, s)
        x, g = x_new, g_new
    return x, max_iter

f = lambda p: 100 * (p[1] - p[0]**2)**2 + (1 - p[0])**2
grad = lambda p: np.array([-400 * p[0] * (p[1] - p[0]**2) - 2 * (1 - p[0]), 200 * (p[1] - p[0]**2)])
x, its = bfgs(f, grad, [-1.2, 1.0])
print("our BFGS:   x =", np.round(x, 6), " iterations:", its)
res = minimize(f, [-1.2, 1.0], jac=grad, method="BFGS")
print("SciPy BFGS: x =", np.round(res.x, 6), " iterations:", res.nit)
our BFGS:   x = [1. 1.]  iterations: 35
SciPy BFGS: x = [1. 1.]  iterations: 32

Both reach the minimum (1,1)(1, 1) in a few dozen iterations. SciPy's line search enforces the Wolfe conditions (The Wolfe Conditions), which is why its iteration count differs slightly.

Step 2: Bound constraints with projected gradient

Many practical problems only restrict each variable to an interval. Projection onto a box is just clipping, so projected gradient descent is a one-line change (Projected Gradient Descent). We solve non-negative least squares and verify the KKT conditions (The KKT Conditions): at the solution, a variable strictly inside its bounds has zero gradient, and a variable at its lower bound has a non-negative gradient.

python · try it yourself
import numpy as np
from scipy.optimize import nnls

rng = np.random.default_rng(3)
A = rng.normal(size=(30, 6)); b = A @ np.array([1.0, -0.5, 2.0, 0.0, 0.5, -1.0]) + 0.3 * rng.normal(size=30)
L = np.linalg.norm(A, 2)**2
x = np.zeros(6)
for _ in range(5000):
    x = np.clip(x - A.T @ (A @ x - b) / L, 0, None)
g = A.T @ (A @ x - b)
print("projected gradient:", np.round(x, 4) + 0)
print("SciPy nnls:        ", np.round(nnls(A, b)[0], 4) + 0)
active = x < 1e-10
print("active (at 0):", np.nonzero(active)[0].tolist())
print("gradient on free variables is ~0:", bool(np.all(np.abs(g[~active]) < 1e-6)))
print("gradient on active variables >= 0:", bool(np.all(g[active] > -1e-6)))
projected gradient: [1.1337 0.     1.8072 0.1605 0.7292 0.    ]
SciPy nnls:         [1.1337 0.     1.8072 0.1605 0.7292 0.    ]
active (at 0): [1, 5]
gradient on free variables is ~0: True
gradient on active variables >= 0: True

The data were generated with negative coefficients for variables 1 and 5, so the constraint holds them at 0, and the other four variables are free. Both solvers find the same point.

Step 3: An LP and its dual

A workshop makes chairs, tables and shelves. The LP chooses how many of each to make, and the dual prices tell us what an extra unit of each resource is worth (Sensitivity and Shadow Prices). We also solve the dual LP explicitly and check that both optimal values agree, which is strong duality (LP Duality).

python · try it yourself
import numpy as np
from scipy.optimize import linprog

profit = np.array([45.0, 80.0, 30.0])
A = np.array([[5.0, 20.0, 4.0],     # wood (units)
              [10.0, 15.0, 5.0],    # labour (hours)
              [1.0, 2.0, 3.0]])     # finishing (hours)
b = np.array([400.0, 450.0, 120.0])
primal = linprog(-profit, A_ub=A, b_ub=b, bounds=[(0, None)] * 3, method="highs")
dual = linprog(b, A_ub=-A.T, b_ub=-profit, bounds=[(0, None)] * 3, method="highs")
print("plan (chairs, tables, shelves):", np.round(primal.x, 3) + 0)
print("primal profit:", round(-primal.fun, 3), " dual value:", round(dual.fun, 3))
print("shadow prices (wood, labour, finishing):", np.round(dual.x, 4) + 0)
print("solver marginals agree:", bool(np.allclose(dual.x, -primal.ineqlin.marginals)))
plan (chairs, tables, shelves): [15.082 10.656 27.869]
primal profit: 2367.213  dual value: 2367.213
shadow prices (wood, labour, finishing): [0.9016 3.8033 2.459 ]
solver marginals agree: True

Step 4: Branch and bound

Branch and bound (Branch and Bound) solves an integer program by solving LP relaxations. If a relaxation is worse than the best integer solution so far, the whole branch is pruned; otherwise we split on a fractional variable. Here it solves a small knapsack-type problem with two constraints, and SciPy's milp checks the answer.

python · try it yourself
import numpy as np
from scipy.optimize import linprog, milp, LinearConstraint, Bounds

value = np.array([10.0, 13.0, 7.0, 8.0, 12.0])
A = np.array([[3.0, 4.0, 2.0, 3.0, 4.0],
              [2.0, 3.0, 2.0, 1.0, 3.0]])
b = np.array([10.0, 7.0])

def branch_and_bound():
    best_val, best_x, nodes = -np.inf, None, 0
    stack = [[(0, 1)] * 5]
    while stack:
        bounds = stack.pop(); nodes += 1
        r = linprog(-value, A_ub=A, b_ub=b, bounds=bounds, method="highs")
        if r.status != 0 or -r.fun <= best_val + 1e-9:
            continue                                   # infeasible or cannot beat the incumbent
        frac = np.nonzero(np.abs(r.x - np.round(r.x)) > 1e-6)[0]
        if len(frac) == 0:
            best_val, best_x = -r.fun, np.round(r.x)
            continue
        i = frac[0]
        lo, hi = list(bounds), list(bounds)
        lo[i] = (bounds[i][0], np.floor(r.x[i])); hi[i] = (np.ceil(r.x[i]), bounds[i][1])
        stack += [lo, hi]
    return best_val, best_x, nodes

val, x, nodes = branch_and_bound()
print("branch and bound:", x.astype(int).tolist(), " value:", val, " LPs solved:", nodes)
m = milp(-value, constraints=LinearConstraint(A, -np.inf, b), integrality=np.ones(5), bounds=Bounds(0, 1))
print("SciPy milp:      ", np.round(m.x).astype(int).tolist(), " value:", -m.fun)
branch and bound: [1, 1, 0, 1, 0]  value: 31.0  LPs solved: 19
SciPy milp:       [1, 1, 0, 1, 0]  value: 31.0

Step 5: Train a classifier with your BFGS

Finally, the toolkit trains a model. L2-regularized logistic regression has a smooth, strongly convex loss (Optimization for Training ML Models), so BFGS converges to the unique minimizer. We compare the result with scikit-learn, which solves the same problem with L-BFGS (L-BFGS). scikit-learn's C is the inverse of the regularization strength, so λ=1/C\lambda = 1/C when the loss is summed over the samples.

python · try it yourself
import numpy as np
from sklearn.linear_model import LogisticRegression

def backtrack(f, x, fx, g, d, t=1.0, c=1e-4):
    while f(x + t * d) > fx + c * t * (g @ d):
        t *= 0.5
    return t

def bfgs(f, grad, x0, tol=1e-6, max_iter=500):
    x = np.asarray(x0, float); n = len(x); H = np.eye(n); g = grad(x)
    for k in range(max_iter):
        if np.linalg.norm(g) < tol:
            return x, k
        d = -H @ g
        t = backtrack(f, x, f(x), g, d)
        s = t * d; x_new = x + s; g_new = grad(x_new); y = g_new - g
        if y @ s > 1e-12:
            rho = 1 / (y @ s); I = np.eye(n)
            H = (I - rho * np.outer(s, y)) @ H @ (I - rho * np.outer(y, s)) + rho * np.outer(s, s)
        x, g = x_new, g_new
    return x, max_iter

rng = np.random.default_rng(7)
X = rng.normal(size=(200, 3)); w_true = np.array([1.5, -2.0, 0.5])
y = (X @ w_true + 0.3 + 0.5 * rng.normal(size=200) > 0).astype(float)
Xb = np.column_stack([X, np.ones(200)]); lam = 1.0
reg = np.array([1.0, 1.0, 1.0, 0.0])          # do not penalize the intercept
def loss(w):
    z = Xb @ w
    return np.sum(np.logaddexp(0, z) - y * z) + 0.5 * lam * np.sum(reg * w**2)
def grad(w):
    p = 1 / (1 + np.exp(-(Xb @ w)))
    return Xb.T @ (p - y) + lam * reg * w
w, its = bfgs(loss, grad, np.zeros(4))
clf = LogisticRegression(C=1 / lam, tol=1e-10, max_iter=1000).fit(X, y)
print("our BFGS:     ", np.round(w, 4), " iterations:", its)
print("scikit-learn: ", np.round(np.append(clf.coef_[0], clf.intercept_[0]), 4))
print("training accuracy:", float(np.mean(((Xb @ w) > 0) == y)))
our BFGS:      [ 2.8739 -3.0265  1.0943  0.2615]  iterations: 16
scikit-learn:  [ 2.8739 -3.0265  1.0943  0.2615]
training accuracy: 0.95

The two weight vectors agree to the printed digits, because both solvers minimize the same strongly convex function.

Where to go next

  • Replace the backtracking search in Step 1 with a Wolfe line search and compare iteration counts on several start points.
  • Store only the last few (s,y)(\mathbf{s}, \mathbf{y}) pairs to turn BFGS into L-BFGS (L-BFGS) and train Step 5 on 1,000 features.
  • Add best-first node selection or a simple cutting plane to Step 4 and count how many LPs it saves (Cutting Planes).
  • Add an L1 penalty to Step 5 and solve it with FISTA (The Lasso with ISTA and FISTA).
  • For the methods behind deep learning optimizers, continue with Math for Deep Learning & LLMs.

Test yourself

Why does the BFGS code skip the update when the curvature y^T s is not positive?

  1. To save time
  2. Because the update would no longer keep H positive definite
  3. Because the gradient is zero
  4. Because the line search failed

In branch and bound, a node is pruned when…

  1. its LP relaxation is integral or worse than the incumbent, or infeasible
  2. it has more than two fractional variables
  3. it is the first node
  4. the LP solver is slow

At the non-negative least-squares solution, a variable that sits at 0 must have…

  1. a negative gradient component
  2. a non-negative gradient component
  3. a zero gradient component and a positive value
  4. an undefined gradient