How to Calculate MSR in Python

MSR stands for Mean Squared Residuals. MSR can be used to compare the the difference between estimated Y and observed Y in model.

It is ratio between Sum Squared Residuals and the number of observations, i.e., n. The following is the formula of MSR. MSR has the exact same formula as the biased MSE.

\[ MSR=\frac{\sum_{i=1}^{n} (\hat{y_i}-y_i)^2 }{n}\]

How to calculate MSR in Python

Method 1: Use Python Numpy to Calculate MSR

np.square(np.subtract(Y_Observed,Y_Estimated)).mean()

Method 2: Use sklearn.metrics to Calculate MSR

MSR is the same as biased MSE. Thus, we can use the MSE function to calculate MSR.

mean_squared_error(Y_Observed,Y_Estimated)

Example 1: Use Numpy to calculate MSR

The following use Numpy to calculate MSR. In the code, it has the Y observed and Y estimated. Then, it uses np.square(np.subtract(Y_Observed,Y_Estimated)).mean() to calculate MSR.

import numpy as np
# Obseved values
Y_Observed = [5,4,3,5,1,4,5]  
  
# Estimated values
Y_Estimated = [4.4,5.2,2.5,4.5,2,4,4.5]  
  
# Use Numpy to calculate MSR
np.square(np.subtract(Y_Observed,Y_Estimated)).mean()

Output:

0.5071428571428571

Thus, the MSR is 0.51.

Example 2: Use sklearn.metrics to Calculate MSR

The following use sklearn.metrics to calculate MSR. We can use mean_squared_error() to calculate MSR, because MSR has the same formula as biased MSE (see my another tutorial).

from sklearn.metrics import mean_squared_error

import numpy as np
# Obseved values
Y_Observed = [5,4,3,5,1,4,5]  
  
# Estimated values
Y_Estimated = [4.4,5.2,2.5,4.5,2,4,4.5]  

#Use sklearn.metrics mean_squared_error to MSR
mean_squared_error(Y_Observed,Y_Estimated)

Output:

0.5071428571428571

Thus, the MSR is 0.51.


Further Reading