Neural Mastery
← Back to Practice

Mean Squared Error From Scratch

Difficulty: Easy · Concept: Linear Regression — The Cost Function

J=1ni=1n(y^(i)y(i))2J = \frac{1}{n} \sum_{i=1}^{n} (\hat{y}^{(i)} - y^{(i)})^2

MSE is the default regression loss: average the squared difference between each prediction and its true value. It's what Linear Regression minimizes, and it reappears as one term inside more complex losses throughout Deep Learning.

Your task: implement mse(y_true, y_pred) for two equal-length lists of numbers. Raise a ValueError if the lengths don't match, and a ValueError on an empty input (division by zero has no sensible answer here).

Implement it yourself
assert mse([1, 2, 3], [1, 2, 3]) == 0 assert mse([0, 0], [1, 1]) == 1 assert mse([3, -0.5, 2, 7], [2.5, 0.0, 2, 8]) == 0.375 assert mse([1], [3]) == 4

Next: Weighted RMSE (a harder variant), or skip ahead to One Gradient Descent Step for Linear Regression

Last updated Sep 5, 2026Edit this pageReport an issue