Skip to main content
© 2026 ePowerAI. All rights reserved.
CoursesContact
eAI
CoursesContact
Week 5: Classification Losses
Optimization
01Week 1: Optimization for Learning
02Week 2: Convex Sets and Functions
03Week 3: Gradient Descent Theory
04Week 4: Least Squares and Conditioning
05Week 5: Classification Losses
06Week 6: Stochastic Gradient Descent
07Week 7: Momentum and Acceleration
08Week 8: Adaptive First-Order Methods
09Week 9: Practical Training Dynamics
10Week 10: Nonsmooth and Composite Objectives
11Week 11: Constraints: Projections and Penalties
12Week 12: Duality for Practitioners
13Week 13: Nonconvex Deep Learning
14Week 14: Capstone — Theory Meets Training
Week 05· Optimization· Model problems22 min read

Week 5: Classification Losses

✦Learning Outcomes
  • Write the logistic loss for binary classification and compute its gradient
  • Derive the softmax function and cross-entropy for multi-class classification
  • Prove the logistic loss is convex
  • Connect cross-entropy to maximum likelihood (pointer, not full MLE derivation)
◆Prerequisites

Background: Weeks 1–2 (ERMEmpirical Risk Minimization, convexity). Week 4's least squares shows the regression side; this week covers the classification analogue.

Later weeks: The softmax and cross-entropy gradients are the default output layer in most deep networks, making this the optimisation face of what the Probability & Statistics course teaches from the modelling side.

Binary Classification Setup#

In binary classification, labels are y∈{0,1}y \in \{0, 1\}y∈{0,1}. The model outputs a real-valued score z=wTxz = w^T xz=wTx (logit), which is squashed through the sigmoid function to produce a probability:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}σ(z)=1+e−z1​

The sigmoid maps R→(0,1)\mathbb{R} \to (0, 1)R→(0,1), with σ(0)=0.5\sigma(0) = 0.5σ(0)=0.5, σ(z)→1\sigma(z) \to 1σ(z)→1 as z→∞z \to \inftyz→∞, and σ(z)→0\sigma(z) \to 0σ(z)→0 as z→−∞z \to -\inftyz→−∞. Its derivative is clean:

σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z))σ′(z)=σ(z)(1−σ(z))

The logistic loss (also called binary cross-entropy) for a single example is:

ℓ(y^,y)=−ylog⁡y^−(1−y)log⁡(1−y^)where y^=σ(wTx)\ell(\hat y, y) = -y \log \hat y - (1-y) \log (1-\hat y) \quad \text{where } \hat y = \sigma(w^T x)ℓ(y^​,y)=−ylogy^​−(1−y)log(1−y^​)where y^​=σ(wTx)

When y=1y=1y=1, the loss is −log⁡y^-\log \hat y−logy^​ — heavily penalises y^≈0\hat y \approx 0y^​≈0. When y=0y=0y=0, the loss is −log⁡(1−y^)-\log(1-\hat y)−log(1−y^​) — heavily penalises y^≈1\hat y \approx 1y^​≈1.

Logistic Regression Gradient#

For one example, the gradient with respect to www is:

∇wℓ=(σ(wTx)−y) x\nabla_w \ell = (\sigma(w^T x) - y) \, x∇w​ℓ=(σ(wTx)−y)x

The derivation uses the chain rule and the sigmoid derivative:

∂ℓ∂w=(−yσ+1−y1−σ)⋅σ(1−σ)⋅x=(σ−y)x\frac{\partial \ell}{\partial w} = \left(\frac{-y}{\sigma} + \frac{1-y}{1-\sigma}\right) \cdot \sigma(1-\sigma) \cdot x = (\sigma - y) x∂w∂ℓ​=(σ−y​+1−σ1−y​)⋅σ(1−σ)⋅x=(σ−y)x

The result is remarkably simple: the gradient is the feature vector weighted by the prediction error. This is the classification analogue of the least squares gradient (wTx−y)x(w^T x - y)x(wTx−y)x.

For the full dataset, the ERM objective and its gradient are:

J(w)=−1n∑i=1n[yilog⁡σ(wTxi)+(1−yi)log⁡(1−σ(wTxi))]J(w) = -\frac{1}{n} \sum_{i=1}^n \left[y_i \log \sigma(w^T x_i) + (1-y_i) \log (1 - \sigma(w^T x_i))\right]J(w)=−n1​∑i=1n​[yi​logσ(wTxi​)+(1−yi​)log(1−σ(wTxi​))]

∇J(w)=1n∑i=1n(σ(wTxi)−yi) xi\nabla J(w) = \frac{1}{n} \sum_{i=1}^n (\sigma(w^T x_i) - y_i) \, x_i∇J(w)=n1​∑i=1n​(σ(wTxi​)−yi​)xi​

Worked numeric example:

Take w=(1,−1)w = (1, -1)w=(1,−1), x=(2,1)x = (2, 1)x=(2,1), y=1y = 1y=1. Then z=wTx=1⋅2+(−1)⋅1=1z = w^T x = 1 \cdot 2 + (-1) \cdot 1 = 1z=wTx=1⋅2+(−1)⋅1=1, y^=σ(1)=1/(1+e−1)≈0.731\hat y = \sigma(1) = 1/(1+e^{-1}) \approx 0.731y^​=σ(1)=1/(1+e−1)≈0.731. The gradient is (y^−y)x=(0.731−1)(2,1)=(−0.538,−0.269)(\hat y - y)x = (0.731 - 1)(2, 1) = (-0.538, -0.269)(y^​−y)x=(0.731−1)(2,1)=(−0.538,−0.269).

The loss is −log⁡(0.731)≈0.313-\log(0.731) \approx 0.313−log(0.731)≈0.313. If the model had been perfectly confident (y^≈1\hat y \approx 1y^​≈1), the loss would be near 0.

Softmax and Multi-Class#

For KKK classes, the model outputs KKK logits z1,…,zKz_1, \ldots, z_Kz1​,…,zK​ (typically z=Wxz = W xz=Wx where W∈RK×dW \in \mathbb{R}^{K \times d}W∈RK×d). The softmax function converts these to a probability distribution:

y^k=softmax(z)k=ezk∑j=1Kezj\hat y_k = \text{softmax}(z)_k = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}y^​k​=softmax(z)k​=∑j=1K​ezj​ezk​​

Softmax outputs sum to 1 and are all positive. The cross-entropy loss for true class y∈{1,…,K}y \in \{1, \ldots, K\}y∈{1,…,K} is:

ℓ=−log⁡y^y=−zy+log⁡∑j=1Kezj\ell = -\log \hat y_y = -z_y + \log \sum_{j=1}^K e^{z_j}ℓ=−logy^​y​=−zy​+log∑j=1K​ezj​

The gradient with respect to the logits has a clean form:

∂ℓ∂zk=y^k−1[k=y]\frac{\partial \ell}{\partial z_k} = \hat y_k - \mathbf{1}[k = y]∂zk​∂ℓ​=y^​k​−1[k=y]

where 1[k=y]\mathbf{1}[k = y]1[k=y] is 1 if kkk is the true class, 0 otherwise. So the gradient vector is y^−ey\hat y - e_yy^​−ey​ where eye_yey​ is the one-hot encoding of the true label. By the chain rule, ∇Wℓ=(y^−ey)xT\nabla_W \ell = (\hat y - e_y) x^T∇W​ℓ=(y^​−ey​)xT.

Again, the gradient is the probability-error-weighted feature vector — exactly the same structural form as the binary case.

Convexity of Logistic Loss#

For a single example, the logistic loss ℓ(w)=−ylog⁡σ(wTx)−(1−y)log⁡(1−σ(wTx))\ell(w) = -y \log \sigma(w^T x) - (1-y)\log(1-\sigma(w^T x))ℓ(w)=−ylogσ(wTx)−(1−y)log(1−σ(wTx)) is convex in www. The Hessian is:

∇2ℓ(w)=σ(wTx)(1−σ(wTx))⋅xxT\nabla^2 \ell(w) = \sigma(w^T x)(1 - \sigma(w^T x)) \cdot x x^T∇2ℓ(w)=σ(wTx)(1−σ(wTx))⋅xxT

The term σ(1−σ)>0\sigma(1-\sigma) > 0σ(1−σ)>0 (the sigmoid output is always strictly between 0 and 1), and xxTx x^TxxT is PSD. Therefore ∇2ℓ(w)⪰0\nabla^2 \ell(w) \succeq 0∇2ℓ(w)⪰0 for all www — the function is convex.

For the full dataset, the Hessian is:

∇2J(w)=1nXTDXwhere D=diag(σ(wTxi)(1−σ(wTxi)))\nabla^2 J(w) = \frac{1}{n} X^T D X \quad \text{where } D = \text{diag}(\sigma(w^T x_i)(1 - \sigma(w^T x_i)))∇2J(w)=n1​XTDXwhere D=diag(σ(wTxi​)(1−σ(wTxi​)))

Since DDD has positive entries on the diagonal, D≻0D \succ 0D≻0, making XTDXX^T D XXTDX PSD. The logistic regression objective is convex.

However, logistic regression is not strongly convex unless XXX has full column rank and the data is non-separable. When the data is linearly separable, ∥w∥→∞\|w\| \to \infty∥w∥→∞ can drive the loss arbitrarily close to 0 (no finite minimiser — this motivates regularisation).

Loss and Likelihood#

Minimising cross-entropy (logistic loss) is equivalent to maximum likelihood estimation (MLEMaximum Likelihood Estimation) under a Bernoulli model. The probability of label yyy given features xxx and parameters www is:

P(y∣x;w)=σ(wTx)y(1−σ(wTx))1−yP(y \mid x; w) = \sigma(w^T x)^y (1 - \sigma(w^T x))^{1-y}P(y∣x;w)=σ(wTx)y(1−σ(wTx))1−y

The log-likelihood of the full dataset is ∑ilog⁡P(yi∣xi;w)=−∑iℓi(w)\sum_i \log P(y_i \mid x_i; w) = -\sum_i \ell_i(w)∑i​logP(yi​∣xi​;w)=−∑i​ℓi​(w). Maximising the log-likelihood = minimising the cross-entropy loss. This connection — loss functions as negative log-likelihoods — is fundamental to modern ML and will be explored fully in the Probability & Statistics course.

Exercise · Fill in the blank

Compute the sigmoid derivative at $z = 0$: $\\sigma'(0) = ___$.

Question 1 of 4

The gradient of the logistic loss for one example (x, y) with y ∈ {0,1} is:

(σ(w^T x) − y) x
σ(w^T x) x
y − σ(w^T x)
x / σ(w^T x)

Browser lab#

Plot the logistic loss surface in 2D (weight space) for a small synthetic dataset, and run GD to find the decision boundary.

python · runs in browser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
n = 100
X_pos = rng.normal(loc=[2, 2], scale=1.0, size=(n//2, 2))
X_neg = rng.normal(loc=[-2, -2], scale=1.0, size=(n//2, 2))
X = np.vstack([X_pos, X_neg])
y = np.hstack([np.ones(n//2), np.zeros(n//2)])

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def loss_and_grad(w, X, y):
    logits = X @ w
    preds = sigmoid(logits)
    eps = 1e-15
    loss = -np.mean(y * np.log(preds + eps) + (1 - y) * np.log(1 - preds + eps))
    grad = X.T @ (preds - y) / len(y)
    return loss, grad

w = np.zeros(2)
eta = 1.0
losses = []
for _ in range(100):
    loss, grad = loss_and_grad(w, X, y)
    losses.append(loss)
    w -= eta * grad

print(f"Final w: {w}")
print(f"Final loss: {loss:.6f}")
print(f"Decision boundary: x2 = {-w[0]/w[1]:.3f} x1")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5))
ax1.scatter(X_pos[:, 0], X_pos[:, 1], c="tab:blue", alpha=0.6, label="y=1")
ax1.scatter(X_neg[:, 0], X_neg[:, 1], c="tab:red", alpha=0.6, label="y=0")
xx = np.linspace(-5, 5, 100)
ax1.plot(xx, -w[0]/w[1] * xx, "k--", label="decision boundary")
ax1.set_xlim(-5, 5); ax1.set_ylim(-5, 5)
ax1.set_xlabel("x1"); ax1.set_ylabel("x2")
ax1.set_title("Data and Learned Decision Boundary")
ax1.legend()
ax2.plot(losses)
ax2.set_xlabel("Iteration"); ax2.set_ylabel("Logistic Loss")
ax2.set_title("Loss vs Iteration")
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
← Previous
Week 4: Least Squares and Conditioning
Next →
Week 6: Stochastic Gradient Descent
On this page
  • Binary Classification Setup
  • Logistic Regression Gradient
  • Softmax and Multi-Class
  • Convexity of Logistic Loss
  • Loss and Likelihood
  • Browser lab