Wednesday, February 18, 2026

Mean Squared Error (MSE) With Python Examples

Mean Squared Error (MSE) is one of the most widely used metrics for evaluating the performance of regression models. It evaluates the prediction accuracy by measuring the average squared difference between predicted and actual values.

Mean Squared Error (MSE) equation

The formula for the mean squared error is-

$$ MSE=\frac{1}{n}\sum _{i=1}^n(y_i-\hat {y}_i)^2 $$

Here n is the total number of observations

yi is the actual value

\(\hat {y}_i \) is the predicted value

The MSE measures the average of the squared differences between predicted values and actual target values, which leads to the following characteristics-

  1. It’s in squared units of the target variable, so it’s not directly intuitive.
  2. MSE Penalizes Large Errors. If your dataset has extreme values, MSE will reflect them strongly. Which means it is sensitive to outliers. For example, an error of 10 when squared- 102=100. At the same time an error of 100 when squared- 1002=10,000
  3. Smaller the MSE, better the model’s prediction accuracy.
  4. Values of MSE may be used for comparing two or more statistical models, in case multiple models are considered for the dataset. Model with lowest MSE is deemed better

MSE calculation example using Numpy in Python

import numpy as np
y_test = [6295, 10698, 13860, 13499, 15750]
y_pred = [5691, 12380, 18371, 15935, 22500]

mse = np.mean(np.square(np.subtract(y_test, y_pred)))
print(mse)

Output

15007931.4

MSE calculation example using sklearn in Python

from sklearn.metrics import mean_squared_error
y_test = [6295, 10698, 13860, 13499, 15750]
y_pred = [5691, 12380, 18371, 15935, 22500]
mse = mean_squared_error(y_test, y_pred)
print(mse)

Output

15007931.4

That's all for this topic Mean Squared Error (MSE) With Python Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Encapsulation in Python
  2. R-squared - Coefficient of Determination
  3. Mean, Median and Mode With Python Examples
  4. Simple Linear Regression With Example
  5. Multiple Linear Regression With Example

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Local, Nonlocal And Global Variables in Python
  3. Python count() method - Counting Substrings
  4. Python Functions : Returning Multiple Values
  5. Marker Interface in Java
  6. Functional Interfaces in Java
  7. Difference Between Checked And Unchecked Exceptions in Java
  8. Race Condition in Java Multi-Threading

No comments:

Post a Comment