Implement a function to compute the gradient of the Mean Squared Error (MSE) loss with respect to predictions, a crucial step in training models using optimization techniques. This task involves understanding the mathematical foundation of MSE and its derivative.
The Mean Squared Error is a measure of the average squared difference between predictions y^ and actual targets y, given by the formula n1∑i=1n(y^i−yi)2. To minimize this loss, we need to calculate its gradient with respect to each prediction y^i.
Here are the steps to calculate the gradient:
Define the MSE loss function.
Apply the chain rule and the sum rule of calculus to differentiate the MSE loss with respect to each y^i.
MSE=n1i=1∑n(y^i−yi)2
This technique is widely used in machine learning for training regression models.
Example
Input
mse_gradient([2.0, 4.0], [1.0, 3.0])
Output
[1.0, 1.0]
Reasoning
Inputs:predictionsy^=[2.0,4.0] and targetsy=[1.0,3.0], two equal-length lists, so n=2. The loss here is MSE=21[(2−1)2+(4−3)2]=1.
Math: only the i-th term of the sum contains y^i, so every other term differentiates to 0. The chain rule on (y^i−yi)2 brings down a factor of 2, and the n1 in front stays, giving ∂y^i∂MSE=n2(y^i−yi).
Plugging in: both errors are 2−1=1 and 4−3=1, so each component is 22⋅1=1.
Output:[1.0, 1.0], one partial derivative per prediction, rounded to 4 decimal places.
Notice: the sign follows the error. A prediction above its target gets a positive gradient (lowering it reduces the loss), one below gets a negative gradient, and a perfect prediction gets 0. Larger n shrinks every component by the n2 factor.
Constraints
Both predictions and targets have n elements where 1 ≤ n ≤ 1000
Return the gradient vector rounded to 4 decimal places
The gradient of MSE with respect to predictions comes from applying basic derivative rules (chain rule and power rule) to a common loss used in regression. MSE measures the average squared difference between predictions y^ and targets y, and its gradient tells you how to change y^ (or the model parameters that produce y^) to reduce this error most quickly. Understanding this gradient is essential because it is what drives gradient descent and backpropagation in neural networks.
For each sample i, the MSE includes a term (y^i−yi)2. The derivative of this term with respect to y^i is proportional to the error(y^i−yi) itself, scaled by constants from the square and the averaging over n. That is why the gradient looks like a scaled version of the prediction error and points in the direction that reduces the discrepancy between predictions and targets.
1. Background Knowledge
Mean Squared Error (MSE)
MSE for predictions y^∈Rn and targets y∈Rn is
MSE(y^,y)=n1i=1∑n(y^i−yi)2.
It is a scalar function of the vector y^.
Partial derivatives and gradients
The gradient of a scalar function L(y^) with respect to the vector y^ is
∇y^L=∂y^1∂L⋮∂y^n∂L.
Each component is found by treating all other y^j as constants and differentiating with respect to y^i.
Derivative rules you need
Power rule: dxd(x2)=2x.
Chain rule: for f(g(x)), dxdf(g(x))=f′(g(x))g′(x).
Linearity: derivative of a sum is the sum of derivatives; constants factor out:
dxd(n1i∑fi(x))=n1i∑fi′(x).
2. Algorithm / Approach Pattern
To get the gradient of a loss like MSE with respect to predictions:
Write the loss explicitly as a sum over individual sample terms.
Pick a single prediction componenty^i and compute \frac{\partial}{\partial \hat y_i} of the loss.
Use linearity: constants and terms not involving y^i disappear or factor out.
Differentiate the remaining term using the power rule and a simple chain rule.
Vectorize the result to write the gradient in compact form for all i.
This is the standard pattern for deriving gradients of averaged per-sample losses.
3. Step-by-Step Strategy
Start from the definition
MSE=n1k=1∑n(y^k−yk)2.
Focus on one component y^i
Compute
∂y^i∂MSE=∂y^i∂(n1k=1∑n(y^k−yk)2).
Use linearity of derivative
For k=i, (y^k−yk)2 does not depend on y^i, so its derivative is 0.
Missing the 1/n factor
Forgetting the averaging leads to gradient 2(y^i−yi) instead of \frac{2}{n}(y^i−yi).
Sign error
The gradient w.r.t. predictions is proportional to y^−y, not y−y^. If you see an extra minus sign, re-check which variable you’re differentiating with respect to.
Confusing gradient w.r.t. predictions vs. parameters
Here you only differentiate with respect to y^. When using backprop, this gradient becomes the “incoming gradient” for the layer that produced y^.
Shape mismatches in vectorized code
Make sure y and y^ have the same shape and that any division by n is broadcast correctly (e.g., avoid integer division in some languages).
5. Time & Space Complexity
Assuming you already have y^ and y:
Time complexity:
Computing the gradient requires one subtraction and one scalar multiplication per element.
Overall: O(n).
Space complexity:
You need space to store the gradient, typically same shape as y^.