JavaScript - Mean absolute error (MAE)
In this short article, we would like to show how to calculate Mean absolute error (MAE) using JavaScript.
MAE is kind of error formula that is useful in many cases.
Mean absolute error formula is:
Where:
n
is the number of the samples,y
is expected sample values,x
is actual sample values.
Mean absolute error can be used in the cases where we are looking for approximated values - used for solved problems where it is not problem if once x(i)
< y(i)
and other time x(i)
> y(i)
. That formula can be used in any modeling technique, e.g. Artificial Inteligence, Kriging, any approximation technique, etc.
Let's suppose we have parabola function values: 0
, 1
, 4
, 9
that were approximated by some technique giving: 0.1
, 0.9
, 3.5
, 10
. The below source code shows how to calulate MAE for them.
xxxxxxxxxx
const calculateMeanAbsoluteError = (y, x) => {
if (y.length === 0 || y.length !== x.length) {
return NaN;
}
let sum = 0;
for (let i = 0; i < y.length; ++i) {
sum += Math.abs(y[i] - x[i]);
}
return sum / y.length;
};
// Usage example:
const y = [0, 1, 4, 9]; // expected values
const x = [0.1, 0.9, 3.5, 10]; // actual values
const error = calculateMeanAbsoluteError(y, x); // MAE
console.log(error); // 0.425
This solution is useful when we collect results during computation, and we don't want to create additional temporary array.
xxxxxxxxxx
const createMeanAbsoluteErrorCalculator = () => {
let sum = 0;
let count = 0;
return {
update: (expected, actual) => {
sum += Math.abs(expected - actual);
count += 1;
},
reset: () => {
sum = 0;
count = 0;
},
calculate: () => sum / count
};
};
// Usage example:
const calculator = createMeanAbsoluteErrorCalculator();
// expected actual
// | |
// v v
calculator.update(0, 0.1);
calculator.update(1, 0.9);
calculator.update(4, 3.5);
calculator.update(9, 10);
const error = calculator.calculate(); // MAE
console.log(error); // 0.425