Mean Squared Error Loss in PyTorch

Basics
BasicsPyTorchLoss FunctionsGoogleMetaAmazon

Problem

Implement mse_loss_tensor(y_pred, y_true) returning the scalar Mean Squared Error MSE=1N∑i=1N(y^i−yi)2\text{MSE} = \frac{1}{N}\sum_{i=1}^N (\hat{y}_i - y_i)^2 as a 0D PyTorch tensor that preserves the autograd computation graph.

Why It Matters: MSE is the standard regression loss in PyTorch; computing it with differentiable tensor operations ensures gradients flow cleanly back into model weights during .backward().

Function Signature

import torch

def mse_loss_tensor(y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
    """Return scalar MSE loss preserving autograd."""

Sample Input & Output

Example 1: Non-Zero Prediction Errors

Input:

y_pred = torch.tensor([2.0, 4.0]), y_true = torch.tensor([1.0, 2.0])

Expected Output:

tensor(2.5)

Explanation: Squared errors are (2-1)^2 = 1 and (4-2)^2 = 4; mean is (1 + 4) / 2 = 2.5.

Example 2: Perfect Predictions

Input:

y_pred = torch.tensor([3.5, -1.0, 0.0]), y_true = torch.tensor([3.5, -1.0, 0.0])

Expected Output:

tensor(0.0)

Explanation: When predictions match targets identically, every residual is 0 so MSE is 0.0.

Constraints & Edge Cases

  • Return a scalar PyTorch tensor.
  • Do NOT call .item() or convert to NumPy—return a PyTorch tensor so loss.backward() still works.
  • Works for any matching tensor shapes (1D or 2D).

Constraints & Evaluation Criteria

  • Return a scalar PyTorch tensor.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[2,4] vs [1,2]
Expected Output / Criteria
loss=2.5, grad=[1.0, 2.0]