Mean Squared Error Gradient
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.
This technique is widely used in machine learning for training regression models.
Example:
mse_gradient([2.0, 4.0], [1.0, 3.0])
[1.0, 1.0]
gradient_i = 2/n × (pred_i - target_i) = 2/2 × 1 = 1 for each
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
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
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:
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 component y^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
- Focus on one component y^i Compute
- Use linearity of derivative
- For k=i, (y^k−yk)2 does not depend on y^i, so its derivative is 0.
- Only the k=i term remains:
- Apply power + chain rule
- Combine
- Vector form (implementation-friendly) If y^ and y are vectors:
In code (NumPy-style):
def mse_gradient(y_pred, y_true):
n = y_true.shape
return (2.0 / n) * (y_pred - y_true)
4. Common Pitfalls
-
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^.
-
Overall: O(n) additional space.