Compute the Sample-Weighted Logistic Log-Loss Gradient From Scratch

Quick Overview

Implement the gradient of a sample-weighted binary log loss for logistic regression in NumPy, normalized by the total weight. It tests the chain rule through the sigmoid, how per-sample weights enter the weight and bias gradients, and why the weight sum is the right normalizer.

Compute the Sample-Weighted Logistic Log-Loss Gradient From Scratch

Role: Data Scientist

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement the gradient of the sample-weighted logistic log loss using NumPy only (no `sklearn`). With `p = sigmoid(X @ w + b)`, `s = sample_weight` and `S = np.sum(s)`, the objective is: ```python J(w, b) = (1/S) * np.sum(s * (-(y*np.log(p) + (1-y)*np.log(1-p)))) ``` ```python def weighted_logistic_gradient(X: np.ndarray, y: np.ndarray, w: np.ndarray, b: float, sample_weight: np.ndarray) -> tuple[np.ndarray, float]: ... ``` Requirements: - `X` is `(n_samples, n_features)` with no column of ones; `b` is a separate scalar intercept. - `y` holds float `0.0`/`1.0` labels, and `sample_weight` is a positive float array of shape `(n_samples,)`. - Normalize by `S`, not by `n_samples`. No regularization. - Return `(grad_w, grad_b)`: `grad_w = X.T @ (s * (p - y)) / S` with shape `(n_features,)`, and `grad_b = np.sum(s * (p - y)) / S` as a float. ```python X = np.array([[1.0, 2.0], [3.0, 4.0]]) y = np.array([0.0, 1.0]) w = np.array([0.0, 0.0]) b = 0.0 sample_weight = np.array([1.0, 3.0]) grad_w, grad_b = weighted_logistic_gradient(X, y, w, b, sample_weight) # grad_w == [-1.0, -1.25], grad_b == -0.25 ``` At zero parameters both probabilities are 0.5, and the total weight is `S = 4`. ```hint Start from one sample Differentiate a single sample's loss with respect to its score `z_i` first. The weight `s_i` and the factor `1/S` are constants in that step. ``` ```hint Two checks for the normalizer Set every weight to 1.0 and compare with the unweighted mean gradient. Then multiply all weights by 10 and see whether the gradient should change. ``` ### Constraints & Assumptions - `X` has shape `(n_samples, n_features)` and contains no intercept column. - `y` and `sample_weight` have shape `(n_samples,)`, and every weight is positive. - Inputs are well shaped and `p` stays strictly inside (0, 1). ### What a Strong Answer Covers - Scales each sample's residual `p - y` by its weight before both reductions. - Normalizes both gradients by the weight sum `S` and adds no regularization. - Returns `grad_w` with shape `(n_features,)` and `grad_b` as a float, using vectorized NumPy. - Derives the weighted residual form with the chain rule and explains why `S` is the right normalizer. ### Follow-up Questions - Why divide by `S` rather than `n_samples`? - How would you add L2 regularization to `grad_w` but not the intercept? - How would you keep `np.log(p)` numerically stable when evaluating the loss? - How do class weights for an imbalanced dataset map onto `sample_weight`?

Overview: Implement the gradient of a sample-weighted binary log loss for logistic regression in NumPy, normalized by the total weight. It tests the chain rule through the sigmoid, how per-sample weights enter the weight and bias gradients, and why the weight sum is the right normalizer.

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

Implement the gradient of the sample-weighted logistic log loss using NumPy only (no sklearn). With p = sigmoid(X @ w + b), s = sample_weight and S = np.sum(s), the objective is:

J(w, b) = (1/S) * np.sum(s * (-(y*np.log(p) + (1-y)*np.log(1-p))))
def weighted_logistic_gradient(X: np.ndarray, y: np.ndarray, w: np.ndarray, b: float, sample_weight: np.ndarray) -> tuple[np.ndarray, float]:
    ...

Requirements:

  • X is (n_samples, n_features) with no column of ones; b is a separate scalar intercept.
  • y holds float 0.0 / 1.0 labels, and sample_weight is a positive float array of shape (n_samples,) .
  • Normalize by S , not by n_samples . No regularization.
  • Return (grad_w, grad_b) : grad_w = X.T @ (s * (p - y)) / S with shape (n_features,) , and grad_b = np.sum(s * (p - y)) / S as a float.
X = np.array([[1.0, 2.0], [3.0, 4.0]])
y = np.array([0.0, 1.0])
w = np.array([0.0, 0.0])
b = 0.0
sample_weight = np.array([1.0, 3.0])
grad_w, grad_b = weighted_logistic_gradient(X, y, w, b, sample_weight)
# grad_w == [-1.0, -1.25], grad_b == -0.25

At zero parameters both probabilities are 0.5, and the total weight is S = 4.

Constraints & Assumptions

  • X has shape (n_samples, n_features) and contains no intercept column.
  • y and sample_weight have shape (n_samples,) , and every weight is positive.
  • Inputs are well shaped and p stays strictly inside (0, 1).

What a Strong Answer Covers Guidance

  • Scales each sample's residual p - y by its weight before both reductions.
  • Normalizes both gradients by the weight sum S and adds no regularization.
  • Returns grad_w with shape (n_features,) and grad_b as a float, using vectorized NumPy.
  • Derives the weighted residual form with the chain rule and explains why S is the right normalizer.

Follow-up Questions Guidance

  • Why divide by S rather than n_samples ?
  • How would you add L2 regularization to grad_w but not the intercept?
  • How would you keep np.log(p) numerically stable when evaluating the loss?
  • How do class weights for an imbalanced dataset map onto sample_weight ?