Logistic regression gradient descent that stops on a gradient-norm tolerance and counts its updates

Quick Overview

Implement full-batch gradient descent for logistic regression in NumPy that stops when the gradient norm falls below a tolerance and counts the updates it applied. It tests the log-loss gradient, where the stopping check belongs, off-by-one counting, and numerical stability of the sigmoid.

Logistic regression gradient descent that stops on a gradient-norm tolerance and counts its updates

Role: Data Scientist

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement full-batch gradient-descent logistic regression from scratch, using NumPy only (no scikit-learn or optimizer library). It stops early when the gradient is small and reports the number of updates it applied. The signature is `def fit_logistic_gd_tol(X, y, lr, max_iter, tol) -> tuple[np.ndarray, float, int]`. Use `p = 1 / (1 + np.exp(-(X @ w + b)))` with a separate scalar `b`. Requirements: - Initialize `w = np.zeros(n_features)` and `b = 0.0`. The learning rate `lr` is fixed, and there is no regularization. - Before each update, compute at the current `(w, b)`: `grad_w = X.T @ (p - y) / n_samples` and `grad_b = np.sum(p - y) / n_samples`. - If `np.linalg.norm(np.concatenate([grad_w, [grad_b]])) < tol` (the L2 norm), stop and return without applying that update. Stopping at the first check gives `n_iter == 0` and the initial `(w, b)`. - Otherwise apply `w -= lr*grad_w` and `b -= lr*grad_b` and count one update, up to `max_iter` updates. A run that never meets the tolerance gives `n_iter == max_iter`. - Return `(w, b, n_iter)`, where `n_iter` is a Python `int` equal to the number of updates actually applied. Example: ```python X = np.array([[1.0], [-1.0]]) y = np.array([1.0, 0.0]) w, b, n_iter = fit_logistic_gd_tol(X, y, lr=1.0, max_iter=100, tol=0.6) # n_iter == 0, w == array([0.]), b == 0.0 (the first gradient norm is 0.5) w, b, n_iter = fit_logistic_gd_tol(X, y, lr=1.0, max_iter=100, tol=0.1) # n_iter == 10, w is about array([2.2632]), b stays at 0 up to rounding ``` ```hint Where the check sits Trace the first pass of the loop when the starting gradient is already below `tol`, and make sure the count and the returned weights match the requirements. ``` ```hint What the norm covers The norm is taken over `grad_w` and `grad_b` together. A test on `grad_w` alone can stop at a different step. ``` ### Constraints & Assumptions - `X` has shape `(n_samples, n_features)` and has no column of ones; the intercept is the separate scalar `b`. - `y` is 1-D with length `n_samples` and holds 0/1 labels. - `lr` is a positive float, `max_iter` is a non-negative integer, and `tol` is a positive float. ### What a Strong Answer Covers - Starts from zeros and computes the mean gradients for `w` and `b` at the current parameters on every pass. - Checks the L2 norm of the combined gradient before each update and returns without applying the update that triggered the stop. - Counts only applied updates, so the count is 0 when the first check stops the loop and `max_iter` when the tolerance is never met, and returns it as a Python `int`. - States the time and memory cost. - Notes the numerical risks: sigmoid overflow at large logits and weights that keep growing on separable data. ### Follow-up Questions - What does a gradient-norm stopping test give you that a test on the change in loss does not? - How would you make the sigmoid numerically stable for large-magnitude logits? - What happens to the weights and the stopping step when the classes are linearly separable, and how would you change the setup?

Overview: Implement full-batch gradient descent for logistic regression in NumPy that stops when the gradient norm falls below a tolerance and counts the updates it applied. It tests the log-loss gradient, where the stopping check belongs, off-by-one counting, and numerical stability of the sigmoid.

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

Implement full-batch gradient-descent logistic regression from scratch, using NumPy only (no scikit-learn or optimizer library). It stops early when the gradient is small and reports the number of updates it applied. The signature is def fit_logistic_gd_tol(X, y, lr, max_iter, tol) -> tuple[np.ndarray, float, int]. Use p = 1 / (1 + np.exp(-(X @ w + b))) with a separate scalar b.

Requirements:

  • Initialize w = np.zeros(n_features) and b = 0.0 . The learning rate lr is fixed, and there is no regularization.
  • Before each update, compute at the current (w, b) : grad_w = X.T @ (p - y) / n_samples and grad_b = np.sum(p - y) / n_samples .
  • If np.linalg.norm(np.concatenate([grad_w, [grad_b]])) < tol (the L2 norm), stop and return without applying that update. Stopping at the first check gives n_iter == 0 and the initial (w, b) .
  • Otherwise apply w -= lr*grad_w and b -= lr*grad_b and count one update, up to max_iter updates. A run that never meets the tolerance gives n_iter == max_iter .
  • Return (w, b, n_iter) , where n_iter is a Python int equal to the number of updates actually applied.

Example:

X = np.array([[1.0], [-1.0]])
y = np.array([1.0, 0.0])

w, b, n_iter = fit_logistic_gd_tol(X, y, lr=1.0, max_iter=100, tol=0.6)
# n_iter == 0, w == array([0.]), b == 0.0  (the first gradient norm is 0.5)

w, b, n_iter = fit_logistic_gd_tol(X, y, lr=1.0, max_iter=100, tol=0.1)
# n_iter == 10, w is about array([2.2632]), b stays at 0 up to rounding

Constraints & Assumptions

  • X has shape (n_samples, n_features) and has no column of ones; the intercept is the separate scalar b .
  • y is 1-D with length n_samples and holds 0/1 labels.
  • lr is a positive float, max_iter is a non-negative integer, and tol is a positive float.

What a Strong Answer Covers Guidance

  • Starts from zeros and computes the mean gradients for w and b at the current parameters on every pass.
  • Checks the L2 norm of the combined gradient before each update and returns without applying the update that triggered the stop.
  • Counts only applied updates, so the count is 0 when the first check stops the loop and max_iter when the tolerance is never met, and returns it as a Python int .
  • States the time and memory cost.
  • Notes the numerical risks: sigmoid overflow at large logits and weights that keep growing on separable data.

Follow-up Questions Guidance

  • What does a gradient-norm stopping test give you that a test on the change in loss does not?
  • How would you make the sigmoid numerically stable for large-magnitude logits?
  • What happens to the weights and the stopping step when the classes are linearly separable, and how would you change the setup?