EasyLoss Functions

Mean Squared Error (MSE)

Loss Functions

Easy

Problem

Compute the mean squared error between predicted and target values:

\operatorname{MSE}=\frac{1}{N}\sum_{i=1}^{N}(\hat{y}_i-y_i)^2

Here, N is the number of values, \hat{y}_i is prediction i, and y_i is its target. Return the result as a Python float.

Theory

Mean Squared Error (MSE) is the most common loss function for regression problems. It measures the average of the squared differences between predicted values and actual values.

The formula:

\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2

Where:


Breaking Down the Computation

The MSE calculation has three steps:

Step 1: Compute the errors (residuals)

Step 2: Square each error

Step 3: Take the mean


A Worked Example

Suppose you have 4 samples:

Sample 1:

Sample 2:

Sample 3:

Sample 4:

Sum of squared errors: 0.25 + 0.04 + 0.49 + 1.00 = 1.78

MSE: \frac{1.78}{4} = 0.445


Why Squaring?

The squaring operation is not arbitrary. It has several important properties:

1. Eliminates sign

2. Penalizes large errors disproportionately

3. Mathematical convenience


The Gradient of MSE

During backpropagation, we need the gradient with respect to each prediction:

\frac{\partial \text{MSE}}{\partial \hat{y}_i} = \frac{2}{n}(\hat{y}_i - y_i)

Key observations:


MSE vs. MAE (Mean Absolute Error)

MAE uses absolute value instead of squaring:

\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|

MSE characteristics:

MAE characteristics:


When MSE Struggles

Outliers

Non-Gaussian error distributions

Different scales


RMSE: Root Mean Squared Error

RMSE is simply the square root of MSE:

\text{RMSE} = \sqrt{\text{MSE}} = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2}

Why use RMSE?

The optimization is identical since taking the square root does not change which model minimizes the loss.


Where MSE Is Used

Examples

Example 1

Input
y_pred = [1.1, 2.1, 2.9, 4.2, 4.8], y_true = [1, 2, 3, 4, 5]
Output
0.022
Explanation
The five squared errors sum to 0.11, which gives a mean of 0.022.

Example 2

Input
y_pred = [1, 2, 3, 4], y_true = [1, 2, 3, 4]
Output
0

Example 3

Input
y_pred = [10.5, 19.5, 30.2], y_true = [10, 20, 30]
Output
0.18

Hints

  1. Convert both inputs with np.asarray(..., dtype=float).
  2. Use np.mean((predictions - targets) ** 2) for the reduction.

Requirements

Constraints

Starter Code

import numpy as np

def mean_squared_error(y_pred: list, y_true: list) -> float:
    """
    Returns the error as a float.
    """
    # Write code here
    pass

Test Cases

CaseMatches
Basic Casepublic
Perfect Predictionspublic
Small Errorspublic