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.
Lesson Videos
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
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
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

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
| Property | Full Hessian H | Hessian-vector product H @ v |
|---|---|---|
| Mathematical Formula | H = (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 Shape | Matrix of size d x d | Vector of size d |
| Computational Complexity | Expensive for large d because the full d x d matrix is built | Faster for large d because it uses matrix-vector products directly |
| Memory Footprint | Massive: stores all pairwise curvature terms | Tiny: stores only vectors/intermediate matrix-vector results |

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?
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.
Sigmoid + Stable Loss
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?
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.
Gradient (Derive ā Implement ā Check)
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.
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?
Convexity & Hessian Intuition
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
Task 3.2: Empirical PSD check
Check that v^T H v >= 0 for random v (PSD).
Explain: Why does PSD imply convexity?
Optimization (Bonus)
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 tow
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.