Logistic regression — the BCE gradient (error × feature)
Background
Differentiating binary cross-entropy looks scary, but the sigmoid factor cancels the from the log and the cross terms vanish, leaving a strikingly simple gradient:
Read it as error × feature: is the prediction error, and multiplying by says "nudge in proportion to how much feature drove that error." It is the same shape as the linear-regression gradient — only changed.
Problem statement
Implement bce_gradient(X, y, y_hat) returning .
Input
X— array-like of shape(m, n): one feature row per example.y— array-like ofmtrue labels (0/1).y_hat— array-like ofmpredicted probabilities.
Output
Returns an np.ndarray of shape (n,): the gradient, one component per feature.
Examples
Example 1 — zero error, zero gradient
Input: X = [[1, 2], [3, 4]], y = [1, 0], y_hat = [1, 0]
Output: [0. 0.]
Explanation: predictions match labels, so and the gradient vanishes.
Example 2
Input: X = [[1, 2], [1, 3]], y = [1, 0], y_hat = [0.5, 0.5]
Output: [0. 0.25]
Explanation: errors are ; , divided by gives .
Constraints
- Use the error (predicted minus true), then project with and divide by .
- Return an
np.ndarrayof shape(n,).
Notes
- This is the gradient you plug into the update to train logistic regression — structurally identical to the linear-regression step from Lesson 1.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: worked two-feature gradient
- •Sample single feature averages the error
- •Example three-row two-feature gradient