PIXELBANKv9.1.0
Menu

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 MSE=1nβˆ‘i=1n(y^iβˆ’yi)2MSE = \frac{1}{n}\sum_{i=1}^{n}(\hat{y}_i - y_i)^2. 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:

  1. Calculate the difference between each predicted value and actual value.
  2. Square each difference and sum them up.
  3. Compute the average of the squared differences.
  4. Calculate the gradient of the MSE loss with respect to each prediction.
βˆ‚MSEβˆ‚y^i=2n(y^iβˆ’yi)\frac{\partial MSE}{\partial \hat{y}_i} = \frac{2}{n}(\hat{y}_i - y_i)

This technique is widely used in deep learning models for regression tasks.

Example:

Input:
mse_grad([2, 4], [1, 3])
Output:
[1.0, 1.0]
Reasoning:
  • Initialize variables: predictions y^=[2,4]\hat{y} = [2, 4], targets y=[1,3]y = [1, 3], and n=2n = 2 (number of samples)
  • Calculate differences: Compute y^iβˆ’yi\hat{y}_i - y_i for each element: [2βˆ’1,4βˆ’3]=[1,1][2-1, 4-3] = [1, 1]
  • Apply gradient formula: Use βˆ‚MSEβˆ‚y^i=2n(y^iβˆ’yi)\frac{\partial MSE}{\partial \hat{y}_i} = \frac{2}{n}(\hat{y}_i - y_i) for each element: 22β‹…[1,1]=[1.0,1.0]\frac{2}{2} \cdot [1, 1] = [1.0, 1.0][1][4]
  • Output result: The gradient is [1.0,1.0][1.0, 1.0], indicating how much each prediction should adjust to reduce the loss[1]

Constraints:

  • Return gradient rounded to 4 decimal places
πŸ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
MSE Loss Gradient - Easy | PixelBank