My Coding > Programming language > Python > Python FAQ > Python: How to calculate MAE - Mean Absolute Error

# Python: How to calculate MAE - Mean Absolute Error

The cost function, or the overall distance between validating set and predicted set is very useful to estimate, how far is your prediction from real data. There are a lot of different cost function. Here I will show you haw to calculate MAE distance

MAE – mean absolute error

MAE = (1/n)*Σni=1(|yi-y’i|)

where y is our target value and y' - our predicted value.

### Test data set

Let’s make a simple dataset for calculation MAE value

 y 5 3 6 7 5 6 3 45 6 8 -3 4 5 y' 4 3 6 6 6 4 4 38 5 7 -4 4 3

and we can transfer these data to python numpy array

``````
y_data = np.array([5, 3,6,7,5,6,3,45,6,8,-3,4,5])
y_pred = np.array([4,3,6,6,6,4,4,38,5,7,-4,4,3])``````

It is possible to use lists as well, but Numpy will give you more options and also will allow you to work with more faster computing by using CUDA.

### Calculating MAE with pure numpy

``````
def MAE(y_validate, y_predict):
return np.mean(np.abs((y_validate - y_predict)))``````

And the final code at one go

``````
import numpy as np
def MAE(y_validate, y_predict):
return np.mean(np.abs((y_validate - y_predict)))
y_data = np.array([5, 3,6,7,5,6,3,45,6,8,-3,4,5])
y_pred = np.array([4,3,6,6,6,4,4,38,5,7,-4,4,3])
print(MAE(y_data, y_pred))
# 1.3846153846153846``````

### Sklearn MAE function

Another way is to use already prepared MAE function in Sclean library (Scikit-learn is a free software machine learning library for the Python programming language). Sometimes it is very useful to know all these functions.

``````
import numpy as np
from sklearn.metrics import mean_absolute_error as mae
y_data = np.array([5, 3,6,7,5,6,3,45,6,8,-3,4,5])
y_pred = np.array([4,3,6,6,6,4,4,38,5,7,-4,4,3])
print(mae(y_data, y_pred))
# 1.3846153846153846``````

Published: 2022-06-18 00:50:35

### 9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.