S30 Logo
S30 AI Labwww.thes30.com
Back
#9

Logistic Regression Gradient & Convexity

MediumšŸŽÆ Classical MLW3 D1

Before You Start

Required knowledge
Logistic regression, derivatives, matrix multiplication, and NumPy.
Libraries used
NumPy
Dataset and source
The notebook's make_data generator creates synthetic binary-classification data, including a separability option.
Expected output
Stable logistic loss and gradients, finite-difference checks, Hessian-vector products, and GD/Newton comparisons.

Logistic Regression, Gradients & Convexity — Theory & Concepts

Read this before attempting the exercises. Logistic regression is the most important baseline in ML and a FAANG interview staple.


1. From Linear to Logistic

Linear regression predicts continuous values. For binary classification, we need probabilities in [0, 1].

Linear:    z = wįµ€x + b           > z ∈ (-āˆž, +āˆž)
Logistic:  p = σ(wįµ€x + b)       > p ∈ (0, 1)

where σ(z) = 1 / (1 + e⁻ᶻ)     < sigmoid function

Sigmoid function curve


2. Numerically Stable Sigmoid

Naive sigmoid overflows for large negative z:

# BAD: exp(1000) overflows
def sigmoid_naive(z):
    return 1 / (1 + np.exp(-z))

# GOOD: stable for all z
def sigmoid(z):
    return np.where(z >= 0,
                    1 / (1 + np.exp(-z)),
                    np.exp(z) / (1 + np.exp(z)))

Interview Tip: Always mention numerical stability when discussing sigmoid or softmax implementations.


3. Binary Cross-Entropy Loss

L(y, p) = -[yĀ·log(p) + (1-y)Ā·log(1-p)]
  • ā—When y=1: loss = -log(p) → penalizes low p
  • ā—When y=0: loss = -log(1-p) → penalizes high p

Binary cross-entropy loss curves for y=1 and y=0

def bce_loss(y, p, eps=1e-15):
    p = np.clip(p, eps, 1 - eps)  # avoid log(0)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

4. Gradient of Logistic Regression

The gradient has a beautifully simple form:

āˆ‚L/āˆ‚w = Xįµ€(σ(Xw) - y) / n

This is: (predictions - labels), projected back through the features. Same structure as linear regression!

def logreg_gradient(X, y, w):
    p = sigmoid(X @ w)
    return X.T @ (p - y) / len(y)

5. Convexity — Why Logistic Regression Always Converges

A function is convex if any line segment between two points lies above the function.

Key property: A convex function has a single global minimum — no local minima traps.

The logistic regression loss is convex because:

  • ā—The Hessian H = Xįµ€DX where D = diag(p(1-p)) is PSD
  • ā—PSD Hessian ⟹ convex function

Interview Tip: "Why is logistic regression preferred as a baseline?" → Convex loss guarantees convergence to global optimum. No hyperparameter sensitivity for optimization.


6. Gradient Descent for Logistic Regression

Logistic Regression Loss Surface and Hessian Curvature

def train_logreg(X, y, lr=0.01, n_steps=1000):
    w = np.zeros(X.shape[1])
    for _ in range(n_steps):
        grad = logreg_gradient(X, y, w)
        w -= lr * grad
    return w

Gradient Check (Finite Differences)

def numerical_grad(f, w, eps=1e-5):
    grad = np.zeros_like(w)
    for i in range(len(w)):
        w_plus = w.copy(); w_plus[i] += eps
        w_minus = w.copy(); w_minus[i] -= eps
        grad[i] = (f(w_plus) - f(w_minus)) / (2 * eps)
    return grad

Relative error should be < 1e-5 for correct implementation.


7. Hessian-Vector Product

The Hessian H = Xįµ€DX is expensive to compute fully (O(d²) storage). Instead, compute Hv directly:

Summary of the Difference

PropertyFull Hessian HHessian-vector product H @ v
Mathematical FormulaH = (1/n) X^T S X, where S = diag(p(1-p))H @ v = (1/n) X^T (s * (X @ v)), where s = p(1-p)
Output ShapeMatrix of size d x dVector of size d
Computational ComplexityExpensive for large d because the full d x d matrix is builtFaster for large d because it uses matrix-vector products directly
Memory FootprintMassive: stores all pairwise curvature termsTiny: stores only vectors/intermediate matrix-vector results

Optimization trajectories: Gradient Descent vs Newton's Method

def hvp(X, w, v):
    p = sigmoid(X @ w)
    d = p * (1 - p)          # diagonal of D
    return X.T @ (d * (X @ v))  # Hv without forming H

ML Use: Second-order methods (L-BFGS, Newton) use Hessian information for faster convergence.


Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!

Ready to practice?

Python 3 — Notebook
0/8 solvedSubstack Notes
1
Dataset & Setup

Logistic Regression Gradient & Convexity — Student Lab

Complete all TODOs. This lab is math-first and stability-first.

Section 0 — Synthetic Dataset

We’ll create a binary classification dataset with both separable and non-separable regimes.

Synthetic dataset (first two features)

Loading editor...
1

Sigmoid + Stable Loss

2
Stable sigmoid
2

Section 1 — Sigmoid + Stable Loss

Task 1.1: Stable sigmoid

Explain: Why does sigmoid saturate for large |z| and what does that do to gradients?

Explain: Why does sigmoid saturate for large |z| and what does that do to gradients?
Loading editor...
3
Stable binary cross-entropy loss
1

Task 1.2: Stable binary cross-entropy loss

We use labels y in {0,1}.

Loss per example: -y log(p) - (1-y) log(1-p) where p=sigmoid(z).

Interview Angle: explain a stable form of log-loss.

Loading editor...
2

Gradient (Derive → Implement → Check)

4
Implement loss and gradient
2

Section 2 — Gradient (Derive → Implement → Check)

Task 2.1: Derive the gradient (write in markdown)

Show that for loss averaged over n examples: grad = X^T (p - y) / n

Checkpoint: What is the shape of grad?

Task 2.2: Implement loss and gradient

FAANG gotcha: ensure y is 0/1, not -1/+1.

Loading editor...
5
Numerical gradient check (finite differences)
1

Task 2.3: Numerical gradient check (finite differences)

Compare your analytic gradient to a central-difference numerical gradient.

Checkpoint: Why can eps too small make the check worse?

Loading editor...
3

Convexity & Hessian Intuition

6
Hessian-vector product (HVP)
2

Section 3 — Convexity & Hessian Intuition

Task 3.1: Hessian-vector product (HVP)

For logistic regression: H = (1/n) X^T S X where S = diag(p(1-p)).

Implement HVP: compute H@v without building full H explicitly.

  • ā—s = p*(1-p)
  • ā—compute Xv then multiply by s then X^T
Loading editor...
7
Empirical PSD check
1

Task 3.2: Empirical PSD check

Check that v^T H v >= 0 for random v (PSD).

Explain: Why does PSD imply convexity?

Explain: Why does PSD imply convexity?
Loading editor...
4

Optimization (Bonus)

8
One step of GD vs Newton (conceptual)
1

Section 4 — Optimization (Bonus)

Task 4.1: One step of GD vs Newton (conceptual)

Implement one gradient descent step. (Newton step is optional.)

FAANG gotcha: perfectly separable data can push weights to infinity; explain why.

Section 4 — GD Step

Gradient descent update rule:

w' = w - Ī· āˆ‡L(w)

Where:

  • ā—w = current weights
  • ā—w' = updated weights after one optimization step
  • ā—Ī· = learning rate (step size)
  • ā—āˆ‡L(w) = gradient of the loss with respect to w

Newton (Hessian) step notation:

w' = w - H(w)^{-1} āˆ‡L(w)

Where:

  • ā—H(w) = āˆ‡Ā²L(w) = Hessian matrix (second derivatives)
  • ā—H(w)^{-1} āˆ‡L(w) rescales the gradient using local curvature

Interpretation: gradient descent uses only slope; Newton step uses slope + curvature for a more curvature-aware update.

Loading editor...

Need help? Share feedback