How to Calculate Mean Absolute Error in Python?
Last Updated :
28 Nov, 2021
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 predicted by the model. It is used to predict the accuracy of the machine learning model.
Formula:
Mean Absolute Error = (1/n) * ∑|yi – xi|
where,
- Σ: Greek symbol for summation
- yi: Actual value for the ith observation
- xi: Calculated value for the ith observation
- n: Total number of observations
Method 1: Using Actual Formulae
Mean Absolute Error (MAE) is calculated by taking the summation of the absolute difference between the actual and calculated values of each observation over the entire array and then dividing the sum obtained by the number of observations in the array.
Example:
Python3
actual = [ 2 , 3 , 5 , 5 , 9 ]
calculated = [ 3 , 3 , 8 , 7 , 6 ]
n = 5
sum = 0
for i in range (n):
sum + = abs (actual[i] - calculated[i])
error = sum / n
print ( "Mean absolute error : " + str (error))
|
Output
Mean absolute error : 1.8
Method 2: Using sklearn
sklearn.metrics module of python contains functions for calculating errors for different purposes. It provides a method named mean_absolute_error() to calculate the mean absolute error of the given arrays.
Syntax:
mean_absolute_error(actual,calculated)
where
- actual- Array of actual values as first argument
- calculated – Array of predicted/calculated values as second argument
It will return the mean absolute error of the given arrays.
Example:
Python3
from sklearn.metrics import mean_absolute_error as mae
actual = [ 2 , 3 , 5 , 5 , 9 ]
calculated = [ 3 , 3 , 8 , 7 , 6 ]
error = mae(actual, calculated)
print ( "Mean absolute error : " + str (error))
|
Output
Mean absolute error : 1.8
Share your thoughts in the comments
Please Login to comment...