Mean Squared Error in Python

Last Updated : 21 Sep, 2026

Mean Squared Error (MSE) is a metric used to measure the difference between actual and predicted values in regression models. It calculates the average of the squared differences between them.

The formula for the mean squared error is:

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

Where:

  • yi: Actual value.
  • y^​i: Predicted value.
  • n: Number of data points.

Calculating MSE

1. Using Scikit-Learn

Scikit-learn provides the mean_squared_error() function to calculate MSE directly.

Python
from sklearn.metrics import mean_squared_error

Y_true = [1, 1, 2, 2, 4]
Y_pred = [0.6, 1.29, 1.99, 2.69, 3.4]

mse = mean_squared_error(Y_true, Y_pred)

print(mse)
Output: 0.21606

Explanation:

  • Y_true contains the actual values.
  • Y_pred contains the predicted values.
  • mean_squared_error() calculates the average squared difference between them.
  • The resulting MSE is 0.21606.

Note: Scikit-learn Install it using pip install scikit-learn before running the code.

2. Using NumPy

MSE can also be calculated using NumPy by finding the differences, squaring them, and calculating their mean.

Python
import numpy as np

Y_true = [1, 1, 2, 2, 4]
Y_pred = [0.6, 1.29, 1.99, 2.69, 3.4]

mse = np.square(np.subtract(Y_true, Y_pred)).mean()
print(mse)

Output
0.21606

Explanation:

  • np.subtract() calculates the difference between actual and predicted values.
  • np.square() squares each difference.
  • .mean() calculates the average of the squared differences.
  • The resulting MSE is 0.21606.
Comment