Friday, December 27, 2024
Google search engine
HomeLanguagesHow to Calculate Mean Absolute Error in Python?

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 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




# Python program for calculating Mean Absolute Error
  
# consider a list of integers for actual
actual = [2, 3, 5, 5, 9]
  
# consider a list of integers for actual
calculated = [3, 3, 8, 7, 6]
  
n = 5
sum = 0
  
# for loop for iteration
for i in range(n):
    sum += abs(actual[i] - calculated[i])
  
error = sum/n
  
# display
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




# Python program for calculating Mean Absolute
# Error using sklearn
  
# import the module
from sklearn.metrics import mean_absolute_error as mae
  
# list of integers of actual and calculated
actual = [2, 3, 5, 5, 9]
calculated = [3, 3, 8, 7, 6]
  
# calculate MAE
error = mae(actual, calculated)
  
# display
print("Mean absolute error : " + str(error))


Output

Mean absolute error : 1.8

RELATED ARTICLES

Most Popular

Recent Comments