Skip to content

← ML Foundations step 5 of 10

Easy Primitives

Implement Mean Squared Error

Mean squared error (MSE) measures how far numerical predictions are from their targets. Subtract each prediction from its target, square the error, and average those squared errors.

For targets [1, 2, 3] and predictions [1, 4, 2], the errors are [0, -2, 1]. Their squares are [0, 4, 1], so the MSE is 5 / 3, approximately 1.666667.

Squaring prevents positive and negative errors from cancelling. It also makes large errors contribute more: an error of 4 contributes 16, while an error of 2 contributes 4. An exact match has zero loss.

Your task

Implement mse_loss(y_true, y_pred) for two nonempty 1D floating-point tensors of the same shape. Return a scalar tensor containing the mean of all squared differences. Do not return the sum or take a square root.

Use basic tensor operations rather than a built-in MSE loss function. Inputs have matching shapes, so you do not need to implement broadcasting or input validation.

The plot shows one prediction against a target of zero. Its height is the squared error for that prediction; this exercise averages such errors.

Loading visualization…