TExcelTAD
Home › Math for Machine Learning › Convex Optimization

Convex Optimization

For general functions, gradient descent may stop at a poor local minimum. For convex functions that cannot happen: every local minimum is a global minimum. Linear regression, logistic regression, ridge, lasso and SVMs all have convex training problems, which is why they train reliably; neural networks do not, which is why their training is an art.

Convex sets and functions

A set C\mathcal{C} is convex if the segment between any two of its points stays inside: for θ∈[0,1]\theta \in [0, 1], θx+(1−θ)y∈C\theta\mathbf{x} + (1 - \theta)\mathbf{y} \in \mathcal{C}. A function ff is convex if its graph lies below every chord:

f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y)f(\theta\mathbf{x} + (1 - \theta)\mathbf{y}) \le \theta f(\mathbf{x}) + (1 - \theta)f(\mathbf{y})

Equivalent tests for smooth ff:

Test Condition
first order f(y)≥f(x)+∇f(x)(y−x)f(\mathbf{y}) \ge f(\mathbf{x}) + \nabla f(\mathbf{x})(\mathbf{y} - \mathbf{x}): tangent planes lie below the graph
second order the Hessian is positive semidefinite everywhere

Building convex functions

Convexity is preserved by non-negative weighted sums, by composing with an affine map (f(Ax+b)f(A\mathbf{x} + \mathbf{b})), and by pointwise maxima. Basic convex functions: ∥x∥\lVert \mathbf{x} \rVert (any norm), ∥x∥2\lVert \mathbf{x} \rVert^2, exe^x, −log⁡x-\log x, log⁡(1+ex)\log(1 + e^x), max⁡(0,1−x)\max(0, 1 - x). From these:

  • least squares ∥Xθ−y∥2\lVert X\boldsymbol{\theta} - \mathbf{y} \rVert^2: norm squared of an affine map;
  • logistic loss ∑nlog⁡(1+e−ynxnTθ)\sum_n\log(1 + e^{-y_n\mathbf{x}_n^T\boldsymbol{\theta}}): sum of a convex function of affine maps;
  • hinge loss plus λ∥θ∥2\lambda\lVert \boldsymbol{\theta} \rVert^2 (the SVM): sum of convex pieces.
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(size=(50, 3)); y = np.sign(rng.normal(size=50))
def logistic_loss(t): return np.sum(np.log1p(np.exp(-y * (X @ t))))
def hessian(t):
    s = 1 / (1 + np.exp(-y * (X @ t)))
    return X.T @ (X * (s * (1 - s))[:, None])           # X^T diag(s(1-s)) X
worst = min(np.linalg.eigvalsh(hessian(rng.normal(size=3) * 3)).min() for _ in range(200))
print("smallest Hessian eigenvalue over 200 random points:", f"{worst:.4f}", "(>= 0: convex)")
# chord test along random segments
ok = True
for _ in range(1000):
    a, b, th = rng.normal(size=3) * 3, rng.normal(size=3) * 3, rng.uniform()
    ok &= logistic_loss(th * a + (1 - th) * b) <= th * logistic_loss(a) + (1 - th) * logistic_loss(b) + 1e-9
print("chord inequality held 1000 times:", bool(ok))
smallest Hessian eigenvalue over 200 random points: 0.0391 (>= 0: convex)
chord inequality held 1000 times: True

Why convexity is so valuable

  1. Local is global. If ∇f(x∗)=0\nabla f(\mathbf{x}^*) = \mathbf{0} for convex ff, then by the first-order test f(y)≥f(x∗)f(\mathbf{y}) \ge f(\mathbf{x}^*) for every y\mathbf{y}.
  2. Convergence guarantees. Gradient descent provably reaches f∗f^*; with strong convexity it converges at a linear (geometric) rate.
  3. Duality is tight under mild conditions, so dual solvers (as for SVMs) find the true optimum.

A non-convex example shows what can go wrong:

python · try it yourself
import numpy as np

f = lambda x: x**4 - 4 * x**2 + x            # two valleys
df = lambda x: 4 * x**3 - 8 * x + 1
for x0 in (-2.0, 2.0):
    x = x0
    for _ in range(500):
        x -= 0.01 * df(x)
    print(f"start {x0:+.0f}: ends at x = {x:.4f}, f = {f(x):.4f}")
start -2: ends at x = -1.4730, f = -5.4442
start +2: ends at x = 1.3470, f = -2.6186

Depending on the start, gradient descent finds a different minimum, and only one of them is global.

In software

  • cvxpy lets you state convex problems declaratively and checks convexity by these composition rules ("disciplined convex programming").
  • scikit-learn's LogisticRegression, Ridge, Lasso and LinearSVC solve convex problems, so their results do not depend on initialization.
  • Deep networks are non-convex; random initialization, SGD noise and over-parameterization make training work in practice anyway.

Exercises

Exercise 1: Convex or not?

Which are convex on R\mathbb{R}? (a) x2+3xx^2 + 3x; (b) sin⁡x\sin x; (c) ∣x−2∣\lvert x - 2 \rvert; (d) −x2-x^2.

Answer

(a) and (c).

Solution

(a) has second derivative 2≥02 \ge 0. (b) has −sin⁡x-\sin x, which changes sign. (c) is a norm of an affine map. (d) has second derivative −2<0-2 < 0: it is concave.

Exercise 2: A convex set?

Is {x∈R2:∥x∥2≥1}\{\mathbf{x} \in \mathbb{R}^2 : \lVert \mathbf{x} \rVert_2 \ge 1\} convex?

Answer

No.

Solution

(1,0)(1, 0) and (−1,0)(-1, 0) are in the set, but their midpoint (0,0)(0, 0) is not. (The unit ball ∥x∥≤1\lVert \mathbf{x} \rVert \le 1 is convex.)

Exercise 3: Hessian test (code)

Is f(x,y)=x2+xy+y2f(x, y) = x^2 + xy + y^2 convex? Check the Hessian's eigenvalues.

Answer

Yes: eigenvalues 1 and 3.

Solution

H=[2112]H = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix} is constant with positive eigenvalues, so ff is (strongly) convex.

python · try it yourself
import numpy as np
print(np.linalg.eigvalsh(np.array([[2.0, 1.0], [1.0, 2.0]])))
[1. 3.]

Test yourself

For a convex differentiable function, a point with zero gradient is…

  1. possibly a saddle point
  2. a global minimum
  3. a maximum
  4. a local minimum that may not be global

Which training problem is NOT convex?

  1. Least squares
  2. Logistic regression
  3. A two-layer neural network with tanh units
  4. Ridge regression

A twice-differentiable function is convex if…

  1. its Hessian is positive semidefinite everywhere
  2. its gradient is zero somewhere
  3. it is bounded
  4. its Hessian is diagonal