CD0009 Logistic Regression From Scratch

Mode B · Build & Trace 30 Min NumPy Only 4 Operation Blanks

Waymo’s driving-log triage team scores each recorded segment with a small calibrated classifier that decides whether it should be routed to human review. The classifier is a binary logistic regression built from first principles in NumPy only: importing scikit-learn, PyTorch, JAX, or any autograd library is forbidden, so every derivative must come from your own derivation.

The feature matrix X has shape (n_samples, n_features) and the label vector y has shape (n_samples,) with entries in \{0, 1\}. Your LogisticRegression class must train with full-batch gradient descent under a fixed learning rate and epoch budget, and expose fit(X, y), predict_proba(X), and predict(X, threshold=0.5). The interviewer will check your gradient derivation on paper before you run anything.

Complete the 4 missing operations in the skeleton below: a numerically stable sigmoid, the forward pass, the vectorized gradient of binary cross-entropy with respect to w and b, and the parameter update with loss logging. Then verify convergence on a linearly separable synthetic set, and explain how you would confirm your gradients with finite differences.

Skeleton Code (Fill Blanks 1-4):

01  import numpy as np
02
03
04  def sigmoid(z: np.ndarray) -> np.ndarray:
05      # TODO (Blank 1): elementwise 1 / (1 + exp(-z)) that stays finite
06      #                 and emits no overflow warning for any finite z
07      return ...
08
09
10  class LogisticRegression:
11      def __init__(self, lr: float = 0.1, epochs: int = 1000):
12          self.lr, self.epochs = lr, epochs
13          self.w, self.b, self.losses = None, 0.0, []
14
15      def predict_proba(self, X: np.ndarray) -> np.ndarray:
16          # TODO (Blank 2): forward pass, X (n_samples, n_features) -> p (n_samples,) in [0, 1]
17          p = ...
18          return p
19
20      def predict(self, X: np.ndarray, threshold: float = 0.5) -> np.ndarray:
21          return (self.predict_proba(X) >= threshold).astype(int)
22
23      def fit(self, X: np.ndarray, y: np.ndarray) -> "LogisticRegression":
24          n_samples, n_features = X.shape
25          self.w, self.b, self.losses = np.zeros(n_features), 0.0, []
26          for _ in range(self.epochs):
27              p = self.predict_proba(X)                     # (n_samples,)
28              # TODO (Blank 3): mean-BCE gradients dw (n_features,) and db (scalar)
29              dw, db = ...
30              # TODO (Blank 4): update w and b; append mean BCE to self.losses
31              ...
32          return self
Operator contract for NumPy logistic regression: inputs X of shape (n_samples, n_features) and y of shape (n_samples,) flow into three question-marked steps (sigmoid plus forward pass, BCE gradients for w and b, update step with loss logging) that repeat for the epoch budget, ending in trained w and b used by predict_proba and predict; bottom boxes list the forbidden libraries, the allowed NumPy building blocks, and the two checks

Figure 1: The input contract is fixed: X of shape (n_samples, n_features) and y of shape (n_samples,) go in, and trained w, b come out. The three question-marked steps inside the epoch loop are yours to write with NumPy alone.

Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the convergence and gradient checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Overflow-Free Sigmoid: Ask which logits can make the argument of np.exp large and positive, and remember that np.where computes both branch arrays before it selects.
(2) 1-D Forward Pass: Probabilities must come out with shape (n_samples,) and a scalar bias broadcast across them, never as an (m, 1) column.
(3) Mean-Reduced Gradient: Derive \partial \mathcal{L} / \partial z on paper before coding; dw must be (n_features,) and both gradients must use the same averaging as the loss.
(4) Descent Step and Safe Logging: Move against the gradient, and make sure a probability that rounds to exactly 0 or 1 cannot turn the logged loss into inf or nan.

2Visual Review Map (Figure 2)
Shape trace for logistic regression: the forward row goes from X (n_samples, n_features) with w (n_features,) and scalar b through Blank 2 logits (n_samples,) and Blank 1 probabilities (n_samples,) to a comparison with y (n_samples,); the backward row goes through Blank 3 gradients dw (n_features,) and scalar db, Blank 4 updated w and b, a logged scalar loss, and loops back for the next epoch; every operation is a question mark

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; the operations that reach them are the exercise.

3Interviewer Nudge & Line Focus

Answer each Socratic check with a shape or a number before you type the NumPy line:

Blank 1 (Stable Sigmoid): In float64, what does np.exp(1000.0) return, and what does exp(z) / (1 + exp(z)) evaluate to at z = +1000? Can you find a single exponent argument that is safe for both signs of z, given that np.where evaluates every branch?
Blank 2 (Forward Pass): X is (n_samples, n_features) and self.w is (n_features,). What shape does their product have, and what shape would p take if w had been stored as an (n, 1) column instead?
Blank 3 (BCE Gradients): Multiply the derivative of the per-example loss with respect to p by the derivative of the sigmoid. What does the product simplify to, which matrix maps an (n_samples,) residual to an (n_features,) gradient, and what must you divide by so the gradient matches a mean loss?
Blank 4 (Update + Logging): If the logged loss rises every epoch, which sign did you flip? And in float64, what does np.log(1 - p) return once a confident logit makes p round to exactly 1.0 (around z = 37)?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *