Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

MSE Loss Gradient

~15 mincode completion

Gradient of MSE Loss

To train a model with gradient descent, we need to compute how the loss changes with respect to the predictions, the gradient .

For MSE loss :

This gradient vector is then backpropagated through the network to update the weights.

Note: prediction minus true (not true minus prediction). Getting this sign wrong flips gradient descent into gradient ascent!

Your task:

Implement mse_gradient(y_true, y_pred) that returns the gradient vector.

Example Tests

y_pred above y_true: positive gradient

Input: {"y_pred":[2,2,2],"y_true":[1,2,3]}

Expected: [0.66667,0,-0.66667]

Perfect predictions: zero gradient

Input: {"y_pred":[1,2,3],"y_true":[1,2,3]}

Expected: [0,0,0]

Single prediction

Input: {"y_pred":[1],"y_true":[3]}

Expected: [-4]

Python
import numpy as np

def mse_gradient(y_true: np.ndarray, y_pred: np.ndarray) -> np.ndarray:
    """
    Compute the gradient of MSE loss w.r.t. predictions.

    Args:
        y_true: Ground truth values, shape (m,)
        y_pred: Predicted values, shape (m,)

    Returns:
        Gradient vector of shape (m,): 2 * (y_pred - y_true) / m
    """
    # YOUR CODE HERE
    pass
Loading docs…