Softmax Loss and Gradient From Scratch for Multinomial Logistic Regression

Quick Overview

Implement the mean cross-entropy loss and its gradient for multinomial logistic regression in NumPy, using a numerically stable softmax and one-hot labels. Tests overflow-safe softmax, vectorized gradient derivation and checking an analytic gradient against finite differences.

Softmax Loss and Gradient From Scratch for Multinomial Logistic Regression

Role: Data Scientist

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `softmax_gradient(W, X, y) -> (loss, grad)` for multinomial logistic regression using NumPy only, without `sklearn`. - `W` has shape `(n_features, n_classes)`. - `X` has shape `(n_samples, n_features)` and is used as given (no intercept column is added). - `y` holds one integer label per sample, each in `0..n_classes-1`. The function must: - Compute the softmax of `X @ W` in a row-max-stable way: subtract `(X @ W).max(axis=1, keepdims=True)` from the logits before exponentiating. - Return `loss` as a Python `float` equal to `-mean_i(sum_j Y1h[i, j] * log(softmax(X @ W)[i, j]))`, where `Y1h = np.eye(n_classes)[y]`. - Return `grad` as a `float64` ndarray of shape `(n_features, n_classes)` equal to `X.T @ (softmax(X @ W) - Y1h) / n_samples`. - Return the tuple `(loss, grad)`. Example: ```python W = np.zeros((3, 2)) # n_features=3, n_classes=2 X = np.array([[1., 0., 0.], [0., 1., 0.]]) y = np.array([0, 1]) loss, grad = softmax_gradient(W, X, y) # loss == log(2) ~ 0.6931 (uniform probabilities at W = 0) # grad == [[-0.25, 0.25], # [ 0.25, -0.25], # [ 0. , 0. ]] # grad.shape == (3, 2) ``` ```hint Taking the log safely If a true-class probability underflows to 0, `np.log` returns `-inf`. Think about getting the log-probabilities from the shifted logits directly instead of taking the log of `P`. ``` ```hint Checking the gradient Before trusting the analytic gradient, compare it with central differences on a small random problem, perturbing one entry of `W` at a time. ``` ### Constraints & Assumptions - NumPy only; no `sklearn` or autodiff library. - `X` is used exactly as given, so there is no intercept term. - Assume `n_samples` is at least 1. - `loss` is graded with `assert_allclose(rtol=1e-5)` and `grad` with `assert_allclose(atol=1e-7)`, where the gradient is checked against a central-difference numerical gradient. ### What a Strong Answer Covers - A softmax that subtracts the per-row maximum, with a reason the shift leaves the probabilities unchanged. - A loss that stays finite and exact when a predicted probability is extremely small. - A fully vectorized gradient with the right shape and the `1 / n_samples` scaling, plus a short derivation of why it has the form given in the task. - A way to verify the analytic gradient numerically. - Time and space cost in terms of samples, features and classes. ### Follow-up Questions - Why is the row-max subtraction numerically necessary, and why does it not change the loss or gradient? - How would you add L2 regularization to both `loss` and `grad`? - The softmax model is over-parameterized. Why does training still work?

Overview: Implement the mean cross-entropy loss and its gradient for multinomial logistic regression in NumPy, using a numerically stable softmax and one-hot labels. Tests overflow-safe softmax, vectorized gradient derivation and checking an analytic gradient against finite differences.

PracHub logo
General
Nov 25, 2026
mediumData ScientistOtherMachine Learning
0
0

Implement softmax_gradient(W, X, y) -> (loss, grad) for multinomial logistic regression using NumPy only, without sklearn.

  • W has shape (n_features, n_classes) .
  • X has shape (n_samples, n_features) and is used as given (no intercept column is added).
  • y holds one integer label per sample, each in 0..n_classes-1 .

The function must:

  • Compute the softmax of X @ W in a row-max-stable way: subtract (X @ W).max(axis=1, keepdims=True) from the logits before exponentiating.
  • Return loss as a Python float equal to -mean_i(sum_j Y1h[i, j] * log(softmax(X @ W)[i, j])) , where Y1h = np.eye(n_classes)[y] .
  • Return grad as a float64 ndarray of shape (n_features, n_classes) equal to X.T @ (softmax(X @ W) - Y1h) / n_samples .
  • Return the tuple (loss, grad) .

Example:

W = np.zeros((3, 2))            # n_features=3, n_classes=2
X = np.array([[1., 0., 0.],
              [0., 1., 0.]])
y = np.array([0, 1])
loss, grad = softmax_gradient(W, X, y)
# loss == log(2) ~ 0.6931 (uniform probabilities at W = 0)
# grad == [[-0.25,  0.25],
#          [ 0.25, -0.25],
#          [ 0.  ,  0.  ]]
# grad.shape == (3, 2)

Constraints & Assumptions

  • NumPy only; no sklearn or autodiff library.
  • X is used exactly as given, so there is no intercept term.
  • Assume n_samples is at least 1.
  • loss is graded with assert_allclose(rtol=1e-5) and grad with assert_allclose(atol=1e-7) , where the gradient is checked against a central-difference numerical gradient.

What a Strong Answer Covers Guidance

  • A softmax that subtracts the per-row maximum, with a reason the shift leaves the probabilities unchanged.
  • A loss that stays finite and exact when a predicted probability is extremely small.
  • A fully vectorized gradient with the right shape and the 1 / n_samples scaling, plus a short derivation of why it has the form given in the task.
  • A way to verify the analytic gradient numerically.
  • Time and space cost in terms of samples, features and classes.

Follow-up Questions Guidance

  • Why is the row-max subtraction numerically necessary, and why does it not change the loss or gradient?
  • How would you add L2 regularization to both loss and grad ?
  • The softmax model is over-parameterized. Why does training still work?