Implement Per-Sample SGD Logistic Regression With a Decaying Learning Rate

Quick Overview

Implement binary logistic regression from scratch with per-sample stochastic gradient descent and a learning rate that decays with a global update counter. It tests the single-sample log-loss gradient, an exact step-size schedule that carries across epochs and reproducible shuffling.

Implement Per-Sample SGD Logistic Regression With a Decaying Learning Rate

Role: Data Scientist

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `fit_logistic_sgd_decay(X, y, lr0, decay, n_epochs, seed)` from scratch (no sklearn): binary logistic regression trained by SGD with one update per sample and a decaying learning rate. Return the learned weights and bias. ```python def fit_logistic_sgd_decay(X: np.ndarray, y: np.ndarray, lr0: float, decay: float, n_epochs: int, seed: int) -> tuple[np.ndarray, float]: ``` The implementation must follow these rules: - Initialize `w = np.zeros(n_features)` and `b = 0.0`. `X` has no ones column (`b` is a separate scalar). - Build `rng = np.random.default_rng(seed)` once before the loop. Each epoch, draw `perm = rng.permutation(n_samples)` from it (no re-seeding) and visit samples in `perm` order. - A global counter `t` starts at 0, increments after every update and never resets between epochs. Use `lr_t = lr0 / (1.0 + decay * t)`, so the first update uses `lr0`. - Run exactly `n_epochs` epochs, with no early stopping and no regularization. - Return `(w, b)`: an `np.ndarray` of shape `(n_features,)` and a `float`. Each sample's update is: ```python p_i = 1 / (1 + np.exp(-(X[i] @ w + b))) w -= lr_t * (p_i - y[i]) * X[i] b -= lr_t * (p_i - y[i]) t += 1 ``` As a check: with `X = [[1.0]]`, `y = [1]`, `lr0 = 1.0`, `decay = 1.0`, `n_epochs = 2` and any seed, the function returns `w` close to `[0.634471]` and `b` close to `0.634471`. ```hint Where the counter lives Decide where `t` is initialized relative to the epoch loop, and check which step size the second epoch's first update should get. ``` ```hint One step, one set of values Within a single sample's update, both parameters should see the same prediction and the same step size. ``` ### Constraints & Assumptions - `X` is a numeric array of shape `(n_samples, n_features)` with no intercept column. - `y` has shape `(n_samples,)` and holds labels 0 or 1. - `lr0` is the initial step size and `decay` sets how fast it shrinks. With `decay = 0` the step size stays constant. ### What a Strong Answer Covers - A global update counter that starts at 0, increments after every update and carries across epochs, so the first update uses exactly `lr0`. - One generator created before the loop, with a fresh permutation drawn from it at the start of every epoch. - The single-sample log-loss gradient, with both updates using the same `p_i` and `lr_t` and no division by `n_samples`. - Return values that match the contract, and the time and space cost of training. ### Follow-up Questions - What changes if `t` resets at the start of every epoch, and why does the spec keep it global? - What conditions on a step-size schedule let SGD converge, and does `lr0 / (1 + decay * t)` meet them? - How would you choose `lr0` and `decay` for a new dataset?

Overview: Implement binary logistic regression from scratch with per-sample stochastic gradient descent and a learning rate that decays with a global update counter. It tests the single-sample log-loss gradient, an exact step-size schedule that carries across epochs and reproducible shuffling.

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

Implement fit_logistic_sgd_decay(X, y, lr0, decay, n_epochs, seed) from scratch (no sklearn): binary logistic regression trained by SGD with one update per sample and a decaying learning rate. Return the learned weights and bias.

def fit_logistic_sgd_decay(X: np.ndarray, y: np.ndarray, lr0: float, decay: float, n_epochs: int, seed: int) -> tuple[np.ndarray, float]:

The implementation must follow these rules:

  • Initialize w = np.zeros(n_features) and b = 0.0 . X has no ones column ( b is a separate scalar).
  • Build rng = np.random.default_rng(seed) once before the loop. Each epoch, draw perm = rng.permutation(n_samples) from it (no re-seeding) and visit samples in perm order.
  • A global counter t starts at 0, increments after every update and never resets between epochs. Use lr_t = lr0 / (1.0 + decay * t) , so the first update uses lr0 .
  • Run exactly n_epochs epochs, with no early stopping and no regularization.
  • Return (w, b) : an np.ndarray of shape (n_features,) and a float .

Each sample's update is:

p_i = 1 / (1 + np.exp(-(X[i] @ w + b)))
w -= lr_t * (p_i - y[i]) * X[i]
b -= lr_t * (p_i - y[i])
t += 1

As a check: with X = [[1.0]], y = [1], lr0 = 1.0, decay = 1.0, n_epochs = 2 and any seed, the function returns w close to [0.634471] and b close to 0.634471.

Constraints & Assumptions

  • X is a numeric array of shape (n_samples, n_features) with no intercept column.
  • y has shape (n_samples,) and holds labels 0 or 1.
  • lr0 is the initial step size and decay sets how fast it shrinks. With decay = 0 the step size stays constant.

What a Strong Answer Covers Guidance

  • A global update counter that starts at 0, increments after every update and carries across epochs, so the first update uses exactly lr0 .
  • One generator created before the loop, with a fresh permutation drawn from it at the start of every epoch.
  • The single-sample log-loss gradient, with both updates using the same p_i and lr_t and no division by n_samples .
  • Return values that match the contract, and the time and space cost of training.

Follow-up Questions Guidance

  • What changes if t resets at the start of every epoch, and why does the spec keep it global?
  • What conditions on a step-size schedule let SGD converge, and does lr0 / (1 + decay * t) meet them?
  • How would you choose lr0 and decay for a new dataset?