#314 · Machine Learning · Medium
⊣ Solve on deep-ml.comImplement the method of Lagrange multipliers to solve a constrained quadratic optimization problem. Given a quadratic objective function and equality constraints, find the optimal point.
import numpy as np
def lagrange_quadratic(Q: np.ndarray, c: np.ndarray,
A: np.ndarray, b: np.ndarray) -> dict:
"""
Solve: minimize (1/2) x^T Q x + c^T x
subject to: A x = b
Q: (n, n) positive definite matrix
c: (n,) linear cost vector
A: (m, n) constraint matrix
b: (m,) constraint values
Uses KKT system:
[Q A^T] [x] = [-c]
[A 0 ] [lam] = [ b]
"""
n = Q.shape[0]
m = A.shape[0]
# Build KKT system
KKT = np.zeros((n + m, n + m))
KKT[:n, :n] = Q
KKT[:n, n:] = A.T
KKT[n:, :n] = A
rhs = np.zeros(n + m)
rhs[:n] = -c
rhs[n:] = b
solution = np.linalg.solve(KKT, rhs)
x_opt = solution[:n]
lambdas = solution[n:]
obj_value = 0.5 * x_opt @ Q @ x_opt + c @ x_opt
return {
"x": x_opt,
"lambdas": lambdas,
"objective_value": float(obj_value),
}