Guide To AI Logo
Unit 15

Optimization for Machine Learning

mathematical methods for finding optimal solutions in learning algorithms

Gradient Descent Contour Minimization
Global MinimumStart (w_0)Step 1Step 2Contours represent levels of equal loss cost f(w)
Read diagram labels
  • Start (w₀)
  • Step 1
  • Step 2
  • Global minimum
  • Contours represent levels of equal loss f(w)

Core Concepts Covered

  • Convex optimization, gradient descent, and SGD
  • Advanced optimizers: Momentum, RMSProp, and Adam
  • Regularization techniques (L1, L2, dropout, early stopping)

1. Objectives, Convexity, and Constraints

Training chooses parameters θ\theta to minimize an objective J(θ)J(\theta). A per-example loss measures prediction error, a regularizer expresses a preference such as small weights, and the objective combines them: J(θ)=1ni=1n(yi,fθ(xi))+λR(θ).J(\theta)=\frac{1}{n}\sum_{i=1}^n\ell(y_i,f_\theta(x_i))+\lambda R(\theta). A metric reports behavior we care about, such as accuracy, and need not be differentiable or identical to the optimized loss.

A function is convex when every chord lies above its graph. For differentiable convex objectives, every local minimum is global; strict convexity gives at most one minimizer. A positive-semidefinite Hessian is a useful twice-differentiable test. Deep networks are generally non-convex and include saddles and flat directions.

Constraints restrict feasible parameters, for example w2c\|w\|_2\leq c. Unit 6 introduced Lagrange multipliers; this unit focuses on iterative algorithms and diagnostics.

Optimizers Follow Different Paths Across a Ravine

SGD oscillationmomentumadaptive scaling
Read diagram labels
  • SGD oscillation
  • momentum
  • adaptive scaling
Worked Example 1

Loss, Regularizer, Objective, and Metric

Problem

Two examples have squared losses 11 and 99. Weights are w=(1,2)w=(1,-2) and λ=0.1\lambda=0.1 with R(w)=w22R(w)=\|w\|_2^2. Find the objective; state a possible metric.

Step-by-step solution

1.Mean data loss is (1+9)/2=5(1+9)/2=5.

2.R(w)=12+(2)2=5R(w)=1^2+(-2)^2=5, so the penalty is 0.1(5)=0.50.1(5)=0.5.

Final answer and interpretation

J=5.5J=5.5. For regression, MAE could be reported even when MSE is optimized.

2. Loss Functions

For a regression residual e=y^ye=\hat y-y, MSE uses e2e^2 and strongly penalizes outliers; MAE uses e|e| and is more robust but has a kink at zero. Huber loss is quadratic for eδ|e|\leq\delta and linear outside: δ(e)={12e2,eδ,δ(e12δ),e>δ.\ell_\delta(e)=\begin{cases}\tfrac{1}{2}e^2,&|e|\leq\delta,\\\delta(|e|-\tfrac{1}{2}\delta),&|e|>\delta.\end{cases}

Binary cross-entropy is [ylogp+(1y)log(1p)]-[y\log p+(1-y)\log(1-p)]. For mutually exclusive classes, softmax gives pj=ezj/kezkp_j=e^{z_j}/\sum_ke^{z_k}, and cross-entropy for true class cc is logpc-\log p_c. Unit 12 explains its information-theoretic meaning.

Hinge loss for y{1,+1}y\in\{-1,+1\} and score ss is max(0,1ys)\max(0,1-ys). It becomes zero once the correct-class score clears the unit margin, matching Unit 13's SVM geometry.

Regression Losses Penalize Residuals Differently

MSE: e²MAE: |e|Huberresidual e
Read diagram labels
  • MSE: e²
  • MAE: |e|
  • Huber
  • residual e
Worked Example 1

Regression Losses Under an Outlier

Problem

Residuals are (1,2,5)(1,-2,5) and Huber uses δ=1\delta=1. Calculate mean MSE, MAE, and Huber loss.

Step-by-step solution

1.MSE is (1+4+25)/3=10(1+4+25)/3=10.

2.MAE is (1+2+5)/3=8/32.67(1+2+5)/3=8/3\approx2.67.

Final answer and interpretation

Huber terms are 0.5,1.5,4.50.5,1.5,4.5, averaging 6.5/32.176.5/3\approx2.17.

MSE lets the large residual dominate; MAE and Huber grow only linearly in the tails.

Worked Example 2

Classification Losses

Problem

For binary y=1,p=0.8y=1,p=0.8, find BCE. For softmax probabilities (0.7,0.2,0.1)(0.7,0.2,0.1) and true class 2, find cross-entropy. For y=1,s=0.4y=-1,s=-0.4, find hinge loss.

Step-by-step solution

1.BCE is log0.80.223-\log0.8\approx0.223.

2.Multiclass cross-entropy is log0.21.609-\log0.2\approx1.609.

Final answer and interpretation

Hinge loss is max(0,1(1)(0.4))=0.6\max(0,1-(-1)(-0.4))=0.6.

3. Batch, Stochastic, and Mini-Batch Gradient Descent

Gradient descent updates wt+1=wtηJ(wt)w_{t+1}=w_t-\eta\nabla J(w_t). Batch descent uses every example for a stable but costly step. SGD uses one random example for a cheap, noisy estimate. Mini-batches average a moderate group, exploiting vectorized hardware while retaining useful gradient noise.

The learning rate η\eta controls step size. Too small wastes computation; too large can oscillate or diverge. Shuffle data and report whether a logged loss is per example, per batch, or an epoch average.

Worked Example 1

Two Gradient Steps by Hand

Problem

Minimize J(w)=(w3)2J(w)=(w-3)^2 from w0=0w_0=0 with η=0.1\eta=0.1.

Step-by-step solution

1.J(w)=2(w3)J'(w)=2(w-3). At w0=0w_0=0, g0=6g_0=-6, so w1=0.6w_1=0.6.

2.At w1=0.6w_1=0.6, g1=4.8g_1=-4.8, so w2=1.08w_2=1.08.

Final answer and interpretation

JJ falls from 99 to 5.765.76 to 3.68643.6864.

4. Momentum, RMSprop, Adam, Schedules, and Convergence

Momentum accumulates velocity, vt=βvt1+(1β)gtv_t=\beta v_{t-1}+(1-\beta)g_t. RMSprop tracks st=ρst1+(1ρ)gt2s_t=\rho s_{t-1}+(1-\rho)g_t^2 and scales the step by 1/(st+ϵ)1/(\sqrt{s_t}+\epsilon), damping coordinates with persistently large gradients.

Adam combines both: mt=β1mt1+(1β1)gtm_t=\beta_1m_{t-1}+(1-\beta_1)g_t, vt=β2vt1+(1β2)gt2v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2, and wt=wt1ηm^tv^t+ϵ.w_t=w_{t-1}-\eta\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}. Warmup, step decay, cosine schedules, or plateau reductions can improve stability.

Convergence may mean small gradients, small objective changes, exhausted compute, or best validation performance. State the criterion and inspect gradient norms, validation curves, and sensitivity to random seeds.

Optimizers Follow Different Paths Across a Ravine

SGD oscillationmomentumadaptive scaling
Read diagram labels
  • SGD oscillation
  • momentum
  • adaptive scaling
Worked Example 1

First Adam Step

Problem

With g1=2g_1=2, m0=v0=0m_0=v_0=0, β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999, η=0.01\eta=0.01, and negligible ϵ\epsilon, find the first update.

Step-by-step solution

1.m1=0.2m_1=0.2 and v1=0.004v_1=0.004.

2.Bias correction gives m^1=2\hat m_1=2 and v^1=4\hat v_1=4.

Final answer and interpretation

The step is 0.01(2)/4=0.010.01(2)/\sqrt{4}=0.01, so w1=w00.01w_1=w_0-0.01.

Bias correction compensates for zero-initialized moment estimates.

5. Regularization, Early Stopping, and Diagnostics

L2L_2 regularization adds λ2w22\frac\lambda2\|w\|_2^2, producing gradient λw\lambda w and discouraging large weights. L1L_1 adds λw1\lambda\|w\|_1 and promotes sparsity. Decoupled weight decay is not always identical to an L2L_2 penalty with adaptive optimizers.

Early stopping saves the checkpoint with the best validation score and halts after a patience window. Both losses staying high suggests underfitting; training loss falling while validation loss rises suggests overfitting. Exploding gradients suggest clipping or a lower rate; flat training may indicate poor scaling, saturation, or a rate that is too small.

Training and Validation Curves Reveal Overfitting

trainingvalidationbest checkpoint
Read diagram labels
  • training
  • validation
  • best checkpoint
Worked Example 1

Regularized Objective and Gradient

Problem

At w=(3,4)w=(3,4), data loss is 1010 with gradient (2,1)(2,-1), and the objective uses 0.22w22\frac{0.2}{2}\|w\|_2^2. Find the objective and total gradient.

Step-by-step solution

1.Penalty is 0.1(9+16)=2.50.1(9+16)=2.5, so J=12.5J=12.5.

2.Its gradient is 0.2w=(0.6,0.8)0.2w=(0.6,0.8).

Final answer and interpretation

Total gradient is (2.6,0.2)(2.6,-0.2).

Worked Example 2

Cumulative Training Diagnostic

Problem

Training losses are (0.9,0.6,0.4,0.3)(0.9,0.6,0.4,0.3) while validation losses are (1.0,0.7,0.55,0.65)(1.0,0.7,0.55,0.65). Which checkpoint should be retained?

Step-by-step solution

1.Validation loss is lowest at epoch 3, so retain that checkpoint.

Final answer and interpretation

At epoch 4 training improves while validation worsens, suggesting overfitting has begun.

Interactive Practice Quiz

Test your understanding with instant feedback

QUESTION 01

For a convex differentiable objective, which statement is guaranteed?

QUESTION 02

Which method updates from one randomly selected training example?

QUESTION 03

What distinguishes Adam from vanilla SGD?

QUESTION 04

What penalty does L2L_2 regularization add?

QUESTION 05

Training loss falls while validation loss begins rising. What is the most likely diagnosis?

QUESTION 06

For residual e=4e=4 and Huber threshold δ=1\delta=1, what is the loss?

QUESTION 07

Which quantity may be non-differentiable because it reports rather than trains?

QUESTION 08

Why does Adam bias-correct its moment estimates?