Algorithms From Scratch

How To Implement Machine Learning Metrics From Scratch in Python

Suresh Madhra·Feb 17, 2026·9 min read

A prediction without a metric is an opinion

Once your model produces predictions you need one number that says whether they are any good — and the choice of number quietly defines what your model will optimise for. This tutorial implements the four metrics you will use most, in plain Python, so their behaviour holds no surprises.

1. Classification accuracy

Simple, intuitive, and dangerous on imbalanced problems. If 98% of transactions are legitimate, predicting "legitimate" every time scores 98%.

accuracy.py

2. Confusion matrix

The confusion matrix is accuracy's honest cousin: it shows you which classes get confused with which. Everything else — precision, recall, F1 — is arithmetic on its four cells.

confusion_matrix.py

3. Mean absolute error

MAE is in the same units as your target and treats every unit of error equally. Report it when a stakeholder asks "how far off are we, typically?"

4. Root mean squared error

RMSE squares errors before averaging, so large misses hurt disproportionately. Use it when a single big error is much worse than several small ones. RMSE is always greater than or equal to MAE; the gap between them tells you how spread out your errors are.

regression_metrics.py

Choosing a metric

  • Balanced classification: accuracy is fine, confusion matrix is better.
  • Imbalanced classification: precision, recall, F1 or ROC AUC — never accuracy alone.
  • Cost-sensitive problems: weight the confusion matrix by the real cost of each error type.
  • Regression with outliers you care about: RMSE. Regression with outliers you do not: MAE.
  • Explaining to a business audience: MAE plus a percentage error, not R².