The Wayback Machine - https://web.archive.org/web/20240920183207/https://www.geeksforgeeks.org/python-mean-squared-error/
Open In App

Python | Mean Squared Error

Last Updated : 30 Jun, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
The Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator measures the average of error squares i.e. the average squared difference between the estimated values and true value. It is a risk function, corresponding to the expected value of the squared error loss. It is always non – negative and values close to zero are better. The MSE is the second moment of the error (about the origin) and thus incorporates both the variance of the estimator and its bias. Steps to find the MSE
  1. Find the equation for the regression line.

    (1)      \begin{equation*}   \hat{Y}_i = \hat{\beta}_0 + \hat{\beta}_1 X_i + \hat{\epsilon}_i   \end{equation*}

  2. Insert X values in the equation found in step 1 in order to get the respective Y values i.e.

    (2)    \begin{equation*} \hat{Y}_i \end{equation*}

  3. Now subtract the new Y values (i.e. \hat{Y}_i) from the original Y values. Thus, found values are the error terms. It is also known as the vertical distance of the given point from the regression line.

    (3)     \begin{equation*}  Y_i - \hat{Y}_i  \end{equation*}

  4. Square the errors found in step 3.

    (4)     \begin{equation*}  {(Y_i - \hat{Y}_i)}^2  \end{equation*}

  5. Sum up all the squares.

    (5)     \begin{equation*}  \sum_{i=1}^{N}(Y_i - \hat{Y}_i)^2  \end{equation*}

  6. Divide the value found in step 5 by the total number of observations.

    (6)     \begin{equation*}  MSE = \frac{1}{N}\sum_{i=1}^{N}(Y_i - \hat{Y}_i)^2  \end{equation*}

Example: Consider the given data points: (1,1), (2,1), (3,2), (4,2), (5,4) You can use this online calculator to find the regression equation / line. Regression line equation: Y = 0.7X – 0.1
X Y \hat{Y}_i
1 1 0.6
2 1 1.29
3 2 1.99
4 2 2.69
5 4 3.4
Now, using formula found for MSE in step 6 above, we can get MSE = 0.21606 MSE using scikit – learn:
from sklearn.metrics import mean_squared_error
  
# Given values
Y_true = [1,1,2,2,4]  # Y_true = Y (original values)
  
# calculated values
Y_pred = [0.6,1.29,1.99,2.69,3.4]  # Y_pred = Y'
  
# Calculation of Mean Squared Error (MSE)
mean_squared_error(Y_true,Y_pred)

                    
Output: 0.21606
MSE using Numpy module:
import numpy as np
  
# Given values
Y_true = [1,1,2,2,4]  # Y_true = Y (original values)
  
# Calculated values
Y_pred = [0.6,1.29,1.99,2.69,3.4]  # Y_pred = Y'
  
# Mean Squared Error
MSE = np.square(np.subtract(Y_true,Y_pred)).mean()

                    
Output: 0.21606


Previous Article
Next Article

Similar Reads

Python - Non-Central Chi-squared Distribution in Statistics
scipy.stats.ncx2() is a non-central chi-squared continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location parameter. Defaul
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
How to Calculate Mean Absolute Error in Python?
Mean Absolute Error calculates the average difference between the calculated values and actual values. It is also known as scale-dependent accuracy as it calculates error in observations taken on the same scale. It is used as evaluation metrics for regression models in machine learning. It calculates errors between actual values and values predicte
2 min read
How To Implement Weighted Mean Square Error in Python?
In this article, we discussed the implementation of weighted mean square error using python. Mean squared error is a vital statistical concept, that is nowadays widely used in Machine learning and Deep learning algorithm. Mean squared error is basically a measure of the average squared difference between the estimated values and the actual value. I
2 min read
How to Navigating the "Error: subprocess-exited-with-error" in Python
In Python, running subprocesses is a common task especially when interfacing with the system or executing external commands and scripts. However, one might encounter the dreaded subprocess-exited-with-error error. This article will help we understand what this error means why it occurs and how to resolve it with different approaches. We will also p
4 min read
How to measure the mean absolute error (MAE) in PyTorch?
In this article, we are going to see how to measure the Mean Absolute Error (MAE) in PyTorch. [Tex]\text{MAE} = \sum\limits_{i = 1}^n {\left| {{y_i} - \widehat {{y_i}}} \right|}[/Tex] The Mean absolute error (MAE) is computed as the mean of the sum of absolute differences between the input and target values. This is an objective function in many of
3 min read
How to Show Mean on Boxplot using Seaborn in Python?
A boxplot is a powerful data visualization tool used to understand the distribution of data. It splits the data into quartiles, and summarises it based on five numbers derived from these quartiles: median: the middle value of data. marked as Q2, portrays the 50th percentile.first quartile: the middle value between "minimum non-outlier" and median.
2 min read
Python - Cumulative Mean of Dictionary keys
Given the dictionary list, our task is to write a Python Program to extract the mean of all keys. Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12}, {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}] Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5,
6 min read
numpy.mean() in Python
numpy.mean(arr, axis = None) : Compute the arithmetic mean (average) of the given data (array elements) along the specified axis. Parameters : arr : [array_like]input array. axis : [int or tuples of int]axis along which we want to calculate the arithmetic mean. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means a
2 min read
Python | Pandas Series.mad() to calculate Mean Absolute Deviation of a Series
Pandas provide a method to make Calculation of MAD (Mean Absolute Deviation) very easy. MAD is defined as average distance between each value and mean. The formula used to calculate MAD is: Syntax: Series.mad(axis=None, skipna=None, level=None) Parameters: axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation. skipn
2 min read
sciPy stats.mean() function | Python
scipy.stats.mean(array, axis=0) function calculates the arithmetic mean of the array elements along the specified axis of the array (list in python). It's formula - Parameters : array: Input array or object having the elements to calculate the arithmetic mean. axis: Axis along which the mean is to be computed. By default axis = 0 Returns : Arithmet
1 min read
Python | Pandas Series.mean()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.mean() function return the mean of the underlying data in the given Series obje
2 min read
Python | Find Mean of a List of Numpy Array
Given a list of Numpy array, the task is to find mean of every numpy array. Let's see a few methods we can do the task. Method #1: Using np.mean() # Python code to find mean of every numpy array in list # Importing module import numpy as np # List Initialization Input = [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([7, 8, 9])] # Output list i
1 min read
Python | Numpy matrix.mean()
With the help of Numpy matrix.mean() method, we can get the mean value from given matrix. Syntax : matrix.mean() Return : Return mean value from given matrix Example #1 : In this example we can see that we are able to get the mean value from a given matrix with the help of method matrix.mean(). # import the important module in python import numpy a
1 min read
Numpy recarray.mean() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record arrays allow the fields to be accessed as members of th
4 min read
Python | Mean of tuple list
Sometimes, while working with Python tuple list, we can have a problem in which we need to find the average of tuple values in the list. This problem has the possible application in many domains including mathematics. Let's discuss certain ways in which this task can be performed. Method #1: Using loops The first approach that can be thought of to
6 min read
Numpy MaskedArray.mean() function | Python
numpy.MaskedArray.mean() function is used to return the average of the masked array elements along given axis.Here masked entries are ignored, and result elements which are not finite will be masked. Syntax : numpy.ma.mean(axis=None, dtype=None, out=None) Parameters: axis :[ int, optional] Axis along which the mean is computed. The default (None) i
3 min read
Python | Harmonic Mean of List
While working with Python, we can have a problem in which we need to find harmonic mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loop + formula The simpler manner to approach this problem is to employ the formula for finding harmonic mean a
5 min read
Python - Ways to find Geometric Mean in List
While working with Python, we can have a problem in which we need to find geometric mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loop + formula The simpler manner to approach this problem is to employ the formula for finding geometric mean
3 min read
Python | Scipy stats.halfgennorm.mean() method
With the help of stats.halfgennorm.mean() method, we can get the value of mean of distribution by using stats.halfgennorm.mean() method. Syntax : stats.halfgennorm.mean(beta) Return : Return the value of mean of distribution. Example #1 : In this example we can see that by using stats.halfgennorm.mean() method, we are able to get the value of mean
1 min read
Python | Scipy stats.hypsecant.mean() method
With the help of stats.hypsecant.mean() method, we can get the value of mean of distribution by using stats.hypsecant.mean() method. Syntax : stats.hypsecant.mean(beta) Return : Return the value of mean of distribution. Example #1 : In this example we can see that by using stats.hypsecant.mean() method, we are able to get the value of mean of distr
1 min read
Python | Mean of consecutive Sublist
Some of the classical problems in programming domain comes from different categories and one among them is finding the mean of subsets. This particular problem is also common when we need to compute the average and store consecutive group mean. Let’s try different approaches to this problem in python language. Method #1 : Using list comprehension +
3 min read
Python | Column Mean in tuple list
Sometimes, while working with records, we can have a problem in which we need to average all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sum() + list comprehension + zip() This task can be perform
4 min read
Python - Inner Nested Value List Mean in Dictionary
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using mean() + loop The
5 min read
Python - Value list Mean
Sometimes, while working with Python dictionary values, we can have problems in which we need to find mean of all the values of all dictionary value lists. This problem can have applications across many domains including web development. Let's discuss certain ways in which this problem can be solved. Input : test_dict = {'best': [11, 21], 'Gfg': [7
6 min read
Python - Kth Index Tuple List Mean
Sometimes, while working with Python tuple, we can have a problem in which we need to compute average of any particular index of tuples in a list. This kind of problem can have application in data domain such as web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [('Gfg', 1), ('is', 5), ('best', 7)],
6 min read
Python - Dictionary Values Mean
Given a dictionary, find the mean of all the values present. Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. Input : test_dict = {"Gfg" : 5, "is" : 10, "Best" : 15} Output : 10.0 Explanation : Mean of these is 10.0Method #1 : Using loop + len() This
4 min read
Python - Get Matrix Mean
Given a Matrix, Find its mean. Input : test_list = [[5, 6, 7], [7, 5, 6]] Output : 6.0 Explanation : 36 / 6 = 6.0 Input : test_list = [[5, 6, 7, 4, 8]] Output : 6.0 Explanation : 30 / 5 = 6.0 Method #1 : Using list comprehension + sum() + len() + zip() The combination of above functions can be used to solve this problem. In this, we perform the mea
7 min read
What does the Double Star operator mean in Python?
Double Star or (**) is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python Language. It is also known as Power Operator. What is the Precedence of Arithmetic Operators? Arithmetic operators follow the same precedence rules as in mathematics, and they are: exponential is performed first, multiplication and division are performed ne
3 min read
Sort Boxplot by Mean with Seaborn in Python
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas.Box Plot is the visual representation of the depicting
3 min read
Practice Tags :