MSE Loss Gradient
Implement a function to compute the gradient of the Mean Squared Error (MSE) loss with respect to predictions. The MSE loss is a common loss function used in regression problems to measure the difference between predicted and actual values.
The MSE loss is calculated as the average of the squared differences between predicted and actual values, which can be expressed as . To update model parameters using backpropagation, we need to compute the gradient of the MSE loss with respect to each prediction.
Here are the steps to compute the gradient:
- Calculate the difference between each predicted value and actual value.
- Square each difference and sum them up.
- Compute the average of the squared differences.
- Calculate the gradient of the MSE loss with respect to each prediction.
This technique is widely used in deep learning models for regression tasks.
Example
mse_grad([2, 4], [1, 3])
[1.0, 1.0]
- Inputs:
predholds the model's predictions andtargetholds the true values , so there are samples. - Errors: each prediction overshoots its target by the same amount: and . For reference the loss itself is , but the gradient doesn't need it.
- Gradient: plug each error into . The factor is , giving for both entries, so the output is
[1.0, 1.0]. - Output: one gradient value per prediction, same length as the inputs, rounded to 4 decimal places.
- Notice: the sign tells the direction. Both values are positive because both predictions are too high, so lowering them reduces the loss. A prediction below its target (e.g. , , ) gives , and a perfect prediction gives .
Constraints
- Return gradient rounded to 4 decimal places