Implement Logistic Regression Gradient Descent That Records Its Loss History

Quick Overview

Implement binary logistic regression with full-batch gradient descent in NumPy and return the mean log-loss recorded before every update. It tests vectorized gradients, the order of logging and updating, exact return shapes and types, and where the plain log-loss formula breaks numerically.

Implement Logistic Regression Gradient Descent That Records Its Loss History

Role: Data Scientist

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement full-batch gradient-descent logistic regression from scratch (no `sklearn`) that records its loss curve. Signature: ```python def fit_logistic_gd_history(X: np.ndarray, y: np.ndarray, lr: float, n_iters: int) -> tuple[np.ndarray, float, np.ndarray]: ``` The implementation must follow these rules: - Initialize `w = np.zeros(n_features)` and `b = 0.0`, with `p = 1/(1+exp(-(X@w + b)))`. - Use mean gradients `dw = X.T @ (p - y) / n_samples` and `db = np.mean(p - y)`, and update `w -= lr*dw`, `b -= lr*db`. - Run exactly `n_iters` iterations with a fixed `lr`: no early stopping, no regularization. - In each iteration, first append the mean log-loss at the current `(w, b)`, then take the step. - Return `(w, b, loss_history)`, where `loss_history` is an `np.ndarray` of shape `(n_iters,)` with dtype `float64`. The loss convention is: ```python loss = -np.mean(y*np.log(p) + (1-y)*np.log(1-p)) # at current (w, b) # loss_history[0] is the loss at the zeros init == log(2) ≈ 0.6931 # history length is EXACTLY n_iters; it does NOT include the loss after the final update ``` ```hint One set of probabilities Each iteration needs `p` twice: once for the loss you record and once for the gradient. Think about where the loss line goes relative to the update. ``` ### Constraints & Assumptions - `X` has shape `(n_samples, n_features)` and has no ones column. `b` is a separate scalar intercept. - `y` is binary `0`/`1` with shape `(n_samples,)`. - Numeric stability guards are out of scope for the required function. ### What a Strong Answer Covers - Correct full-batch updates with mean gradients, starting from the zero initialization and running exactly `n_iters` fixed-step iterations. - Loss recorded at the current parameters before each step, so the first entry is the initialization loss and the history has exactly `n_iters` entries. - Return values with the required shapes and types, including a `float64` history array. - Where the plain log-loss formula breaks numerically, and what a stable version looks like. - The time and space cost of training and of keeping the history. ### Follow-up Questions - How would you add a numerically stable log-loss to avoid `log(0)`? - Why append the loss before the step instead of after? - How would you extend this to mini-batch training or add L2 regularization?

Overview: Implement binary logistic regression with full-batch gradient descent in NumPy and return the mean log-loss recorded before every update. It tests vectorized gradients, the order of logging and updating, exact return shapes and types, and where the plain log-loss formula breaks numerically.

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

Implement full-batch gradient-descent logistic regression from scratch (no sklearn) that records its loss curve. Signature:

def fit_logistic_gd_history(X: np.ndarray, y: np.ndarray, lr: float,
                            n_iters: int) -> tuple[np.ndarray, float, np.ndarray]:

The implementation must follow these rules:

  • Initialize w = np.zeros(n_features) and b = 0.0 , with p = 1/(1+exp(-(X@w + b))) .
  • Use mean gradients dw = X.T @ (p - y) / n_samples and db = np.mean(p - y) , and update w -= lr*dw , b -= lr*db .
  • Run exactly n_iters iterations with a fixed lr : no early stopping, no regularization.
  • In each iteration, first append the mean log-loss at the current (w, b) , then take the step.
  • Return (w, b, loss_history) , where loss_history is an np.ndarray of shape (n_iters,) with dtype float64 .

The loss convention is:

loss = -np.mean(y*np.log(p) + (1-y)*np.log(1-p))  # at current (w, b)
# loss_history[0] is the loss at the zeros init == log(2) ≈ 0.6931
# history length is EXACTLY n_iters; it does NOT include the loss after the final update

Constraints & Assumptions

  • X has shape (n_samples, n_features) and has no ones column. b is a separate scalar intercept.
  • y is binary 0 / 1 with shape (n_samples,) .
  • Numeric stability guards are out of scope for the required function.

What a Strong Answer Covers Guidance

  • Correct full-batch updates with mean gradients, starting from the zero initialization and running exactly n_iters fixed-step iterations.
  • Loss recorded at the current parameters before each step, so the first entry is the initialization loss and the history has exactly n_iters entries.
  • Return values with the required shapes and types, including a float64 history array.
  • Where the plain log-loss formula breaks numerically, and what a stable version looks like.
  • The time and space cost of training and of keeping the history.

Follow-up Questions Guidance

  • How would you add a numerically stable log-loss to avoid log(0) ?
  • Why append the loss before the step instead of after?
  • How would you extend this to mini-batch training or add L2 regularization?