v9.1.1
Menu

Mean Squared Error Gradient

mediumFREECalculus & OptimizationCalculus, Machine LearningCV: Mathematical Foundations

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^\hat{y} and actual targets yy, given by the formula 1n∑i=1n(y^i−yi)2\frac{1}{n}\sum_{i=1}^{n}(\hat{y}_i - y_i)^2. To minimize this loss, we need to calculate its gradient with respect to each prediction y^i\hat{y}_i.

Here are the steps to calculate the gradient:

  1. Define the MSE loss function.
  2. Apply the chain rule and the sum rule of calculus to differentiate the MSE loss with respect to each y^i\hat{y}_i.
MSE=1n∑i=1n(y^i−yi)2\text{MSE} = \frac{1}{n}\sum_{i=1}^{n}(\hat{y}_i - y_i)^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: predictions y^=[2.0,4.0]\hat{y} = [2.0, 4.0] and targets y=[1.0,3.0]y = [1.0, 3.0], two equal-length lists, so n=2n = 2. The loss here is MSE=12[(2−1)2+(4−3)2]=1\text{MSE} = \frac{1}{2}\big[(2-1)^2 + (4-3)^2\big] = 1.
  • Math: only the ii-th term of the sum contains y^i\hat{y}_i, so every other term differentiates to 00. The chain rule on (y^i−yi)2(\hat{y}_i - y_i)^2 brings down a factor of 22, and the 1n\frac{1}{n} in front stays, giving ∂ MSE∂y^i=2n(y^i−yi)\frac{\partial\,\text{MSE}}{\partial \hat{y}_i} = \frac{2}{n}(\hat{y}_i - y_i).
  • Plugging in: both errors are 2−1=12 - 1 = 1 and 4−3=14 - 3 = 1, so each component is 22⋅1=1\frac{2}{2} \cdot 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 00. Larger nn shrinks every component by the 2n\frac{2}{n} factor.

Constraints

  • Both predictions and targets have n elements where 1 ≤ n ≤ 1000
  • Return the gradient vector rounded to 4 decimal places

Learn this in

More from CV: Mathematical Foundations

solution.py

Test results

Sign in to run your code against the test cases.