Implement L2-Penalized Logistic Regression with Full-Batch Gradient Descent

Quick Overview

Implement L2-regularized binary logistic regression in NumPy with full-batch gradient descent, a hand-written sigmoid and a fixed number of iterations. It tests the penalized log-loss gradient, keeping the intercept unpenalized, simultaneous parameter updates and numerical stability.

Implement L2-Penalized Logistic Regression with Full-Batch Gradient Descent

Role: Data Scientist

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `def fit_logistic_l2_gd(X, y, lr, n_iters, lam) -> tuple[np.ndarray, float]`: binary logistic regression trained with full-batch gradient descent, using only `numpy` (implement `sigmoid` yourself). Return `(w, b)` with `w` of shape `(n_features,)` and `b` a float, obtained by running gradient descent on: ```python J(w, b) = -mean(y*log(p) + (1-y)*log(1-p)) + (lam/2) * np.sum(w**2) where p = sigmoid(X @ w + b) ``` The implementation must follow these rules: - Initialize `w = np.zeros(n_features)` and `b = 0.0` (separate intercept: `X` has no ones column). - Use the mean log-loss gradient (divide by `n_samples`). - L2 adds `lam * w` to `grad_w` and nothing to `grad_b` (the intercept is not penalized). - Run exactly `n_iters` iterations with a fixed `lr`, with no early stopping. - Update `w` and `b` simultaneously (compute both gradients before applying either). One iteration looks like this: ```python p = sigmoid(X @ w + b) error = p - y # shape (n_samples,) grad_w = X.T @ error / n + lam * w # penalty on weights only grad_b = error.mean() # no penalty on intercept w -= lr * grad_w b -= lr * grad_b ``` ```hint One p, two gradients Compute `p` once per iteration and build both gradients from it. Then check which of the two gradients the penalty term `(lam/2) * np.sum(w**2)` actually depends on. ``` ### Constraints & Assumptions - `X` has shape `(n_samples, n_features)`. - `y` holds `0`/`1` labels with shape `(n_samples,)`. - Only NumPy is available, so the sigmoid has to be written by hand. ### What a Strong Answer Covers - Zero initialization, a separate intercept, and exactly `n_iters` fixed-step iterations. - The mean log-loss gradient plus `lam * w` on the weights, with no penalty on the intercept. - Simultaneous updates computed from a single set of predictions per iteration. - A hand-written sigmoid that does not overflow for logits of large magnitude. - Return types that match the contract, and the time and space cost of the loop. ### Follow-up Questions - How would you guard against overflow in `sigmoid` for large negative or positive inputs? - Why exclude the intercept from the L2 penalty? - How would this change for mini-batch or stochastic gradient descent?

Overview: Implement L2-regularized binary logistic regression in NumPy with full-batch gradient descent, a hand-written sigmoid and a fixed number of iterations. It tests the penalized log-loss gradient, keeping the intercept unpenalized, simultaneous parameter updates and numerical stability.

General logo
General
Nov 24, 2026
easyData ScientistOtherMachine Learning
0
0

Implement def fit_logistic_l2_gd(X, y, lr, n_iters, lam) -> tuple[np.ndarray, float]: binary logistic regression trained with full-batch gradient descent, using only numpy (implement sigmoid yourself). Return (w, b) with w of shape (n_features,) and b a float, obtained by running gradient descent on:

J(w, b) = -mean(y*log(p) + (1-y)*log(1-p)) + (lam/2) * np.sum(w**2)
where p = sigmoid(X @ w + b)

The implementation must follow these rules:

  • Initialize w = np.zeros(n_features) and b = 0.0 (separate intercept: X has no ones column).
  • Use the mean log-loss gradient (divide by n_samples ).
  • L2 adds lam * w to grad_w and nothing to grad_b (the intercept is not penalized).
  • Run exactly n_iters iterations with a fixed lr , with no early stopping.
  • Update w and b simultaneously (compute both gradients before applying either).

One iteration looks like this:

p = sigmoid(X @ w + b)
error = p - y                       # shape (n_samples,)
grad_w = X.T @ error / n + lam * w  # penalty on weights only
grad_b = error.mean()               # no penalty on intercept
w -= lr * grad_w
b -= lr * grad_b

Constraints & Assumptions

  • X has shape (n_samples, n_features) .
  • y holds 0 / 1 labels with shape (n_samples,) .
  • Only NumPy is available, so the sigmoid has to be written by hand.

What a Strong Answer Covers Guidance

  • Zero initialization, a separate intercept, and exactly n_iters fixed-step iterations.
  • The mean log-loss gradient plus lam * w on the weights, with no penalty on the intercept.
  • Simultaneous updates computed from a single set of predictions per iteration.
  • A hand-written sigmoid that does not overflow for logits of large magnitude.
  • Return types that match the contract, and the time and space cost of the loop.

Follow-up Questions Guidance

  • How would you guard against overflow in sigmoid for large negative or positive inputs?
  • Why exclude the intercept from the L2 penalty?
  • How would this change for mini-batch or stochastic gradient descent?