Mean and absolute error functions
Quick answer
The arithmetic mean is the sum of values divided by their count. A constant baseline predicts the training mean for every new sample. Absolute error is the distance between a prediction and the observed target, ignoring sign. Mean absolute error (MAE) averages those distances and uses the target unit. The mean is a useful baseline; the median, not necessarily the mean, minimizes absolute loss among constant predictions on a dataset.
Fit a training mean
For this small example, all values are finite whole minutes. sum adds values and len counts them. Return None for an empty list, a deliberate contract meaning no mean is defined. It is not a prediction of zero.
def mean(values): if not values: return None return sum(values) / len(values)
print(mean([8, 12, 16]))print(mean([]))Expected output:
12.0NoneThe training mean is 12 minutes. An empty training set cannot fit this baseline.
Evaluate held-out predictions
Use the fitted constant 12 on two new parcels with durations 10 and 16. The absolute errors are 2 and 4, so the MAE is 3 minutes. zip pairs items in order but normally stops at the shorter input, so check lengths first.
def mae(actual, predicted): if not actual or len(actual) != len(predicted): return None return sum(abs(a - p) for a, p in zip(actual, predicted)) / len(actual)
print(mae([10, 16], [12, 12]))print(mae([10], [12, 12]))print(mae([], []))Expected output:
3.0NoneNoneA length mismatch or no evaluation rows yields no score. For real floating-point measurements, validate finite values, define numerical tolerance and retain enough precision before formatting the displayed result.
Common mistakes
Do not fit the constant on the held-out outcomes. Do not average signed errors as a substitute for MAE: +2 and -2 cancel even though both predictions are wrong. Never interpret None as a perfect zero score.
Practice and next steps
Fit the mean of [6, 10, 14], predict two held-out values [7, 15] and compute MAE by hand. Check your implementation against empty inputs and mismatched lengths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mean and absolute error functions — knowledge check
Apply the lesson to small reproducible experiment scenarios.
What is the mean of [6, 10, 14]?
What is MAE for actual [7, 15] and predictions [10, 10]?
Why does the example return None for empty inputs?
Where should the constant baseline be fitted?
What constant minimizes total absolute error on a sample?