Derive the gradient of mean squared error for a linear model

Every regression trainer computes this gradient millions of times. Getting the factor of 2 and the division by n right matters.

Write mse_grad(X, y, w, b). Predictions are X @ w + b. The loss is mean((pred - y) ** 2). Return (grad_w, grad_b).

Signaturedef mse_grad(X, y, w, b)

Example

X = [[1], [2]], y = [1, 2], w = [0], b = 0 gives grad_w [-5] and grad_b -3.

Understand the idea

For a linear model, the gradient of mean squared error says which way to nudge each weight to shrink the average squared mistake. Each residual r = pred - y contributes 2 * r times its input, and averaging divides by n. Worked example: X = [[1], [3]], y = [2, 2], w = [1], b = 0. Predictions [1, 3], residuals [-1, 1]. grad_w = (2 / 2) * (1 * -1 + 3 * 1) = 2. grad_b = (2 / 2) * (-1 + 1) = 0. So the weight should go down and the bias is already balanced. Rule: r = X w + b - y; grad_w = (2 / n) * X^T r; grad_b = (2 / n) * sum(r). Dropping the factor 2 halves every gradient, which training with a fixed learning rate may hide but a gradient check will catch. Forgetting the 1 / n makes the step size grow with the batch size. This is the gradient at the heart of linear regression, and the same pattern appears in the output layer of any network trained with MSE.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplemse_grad([[1], [2]], [1, 2], [0], 0)
  • Sample 2: randommse_grad(_X, _y, _w, 0.3)
  • Test 3: at optimummse_grad([[1.0], [2.0]], [2.0, 4.0], [2.0], 0.0)