TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
←

240. MSE Loss (PyTorch)

Easy

Implement Mean Squared Error in PyTorch using primitive tensor ops only.

Signature: def mse_loss(y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor

The rule: you may NOT call F.mse_loss or nn.MSELoss. Implement the formula yourself.

Allowed primitives: **, .mean(), basic arithmetic.

Formula:

mse(y_pred, y_true) = ((y_pred - y_true) ** 2).mean()

Return type — important: unlike the NumPy version which returns a Python float, the PyTorch version should return a 0-dimensional tensor (the result of .mean()). Do not call .item() — the autograd graph would be broken. The harness compares against a scalar value automatically.

Math

LMSE​=n1​i=1∑n​(y^​i​−yi​)2

Related problems

  • MSE LosseasyNumPy

Asked at

NumPy

import numpy as np

 

def mse_loss(...):

    pass

🔒

Premium problem

Free accounts include problems #1–20. Upgrade to unlock the editor, hidden test cases, and reference solutions for every problem.

Upgrade to PremiumBack to problems

Already premium?