Velamuvi AIAcademy

Lesson 11 of 13 · Getting It Right

Measuring Accuracy

Measure ML models: MAE and RMSE for regression; accuracy, the confusion matrix, precision and recall for classification; and why 99% accuracy can be useless.

  • 9 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • Measure regression models with MAE and RMSE
  • Read a confusion matrix for a classifier
  • Calculate accuracy, precision and recall
  • Choose a metric that matches what mistakes cost
  • Compute the same metrics with scikit-learn and compare against a baseline

Measuring regression models

For models that predict numbers, look at the errors: prediction minus actual value.

Measuring classifiers

For classifiers, every prediction is right or wrong, but there are two different ways to be wrong.

Predicted fraudPredicted genuine
Really fraudTrue positiveFalse negative (missed)
Really genuineFalse positive (false alarm)True negative

Here are both kinds of metric in action, ending with a warning:

Try it yourselfPython
# ---- Regression: how far off are the predictions? ----
actual    = [250, 310, 190, 400, 275]     # house prices in thousands
predicted = [262, 298, 205, 360, 280]

errors = [p - a for p, a in zip(predicted, actual)]
mae = sum(abs(e) for e in errors) / len(errors)
rmse = (sum(e * e for e in errors) / len(errors)) ** 0.5
print(f"Errors: {errors}")
print(f"MAE  (average size of the error):  {mae:.1f}")
print(f"RMSE (punishes big errors more):   {rmse:.1f}")

# ---- Classification: a fraud detector on 1,000 payments ----
# 990 payments are genuine and 10 are fraud. The model flags 12 payments;
# 8 of them really are fraud.
true_positives = 8        # fraud, flagged
false_positives = 4       # genuine, flagged by mistake
false_negatives = 2       # fraud the model missed
true_negatives = 986      # genuine, correctly left alone

total = true_positives + false_positives + false_negatives + true_negatives
accuracy = (true_positives + true_negatives) / total
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
print()
print(f"Accuracy:  {accuracy:.1%}")
print(f"Precision: {precision:.1%}  (of the flagged payments, how many were fraud)")
print(f"Recall:    {recall:.1%}  (of the fraud, how much was caught)")

lazy_accuracy = 990 / 1000       # a "model" that never flags anything
print(f"\nA model that never flags anything: accuracy {lazy_accuracy:.1%}, recall 0%")

The house-price model is off by about 16.8 thousand on average, but RMSE (20.7) is noticeably higher, because one prediction was off by 40.

The fraud detector's 99.4% accuracy sounds superb, but a “model” that never flags anything scores 99.0%, because 99% of payments are genuine. Accuracy hides what matters here. Precision (66.7%: two in three alerts are real fraud) and recall (80%: it catches four frauds in five) tell the real story.

Which metric?

SituationWhat hurts mostFocus on
Screening for a serious diseaseMissing a sick patientRecall (then confirm with further tests)
Spam filterLosing a real email in the spam folderPrecision
Fraud detectionBoth: missed fraud costs money, false alarms annoy customersBalance precision and recall
House pricesBeing far offMAE, and RMSE if big misses are especially costly
Balanced classes, equal costsAny mistakeAccuracy is fine

Metrics in scikit-learn

In real projects you don't count by hand. The sklearn.metrics module computes every metric above from two lists: the real labels and the model's predictions.

The program below creates 1,000 payments, about 3% of them fraud, and compares a baseline that always says “genuine” (DummyClassifier) with a logistic regression model, a simple classifier that outputs a probability for each class. class_weight="balanced" tells the model to treat the rare fraud class as more important, and stratify=y keeps the same 3% fraud share in the training and test sets.

Try it yourselfPython
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split

# 1,000 payments, about 3% fraud (class 1)
X, y = make_classification(n_samples=1000, n_features=6, weights=[0.97], flip_y=0, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

lazy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)   # always says "genuine"
model = LogisticRegression(class_weight="balanced").fit(X_train, y_train)

for name, clf in [("always genuine", lazy), ("logistic model", model)]:
    pred = clf.predict(X_test)
    print(f"{name:<15} accuracy {accuracy_score(y_test, pred):.1%}  "
          f"precision {precision_score(y_test, pred, zero_division=0):.1%}  "
          f"recall {recall_score(y_test, pred):.1%}  F1 {f1_score(y_test, pred):.2f}")

pred = model.predict(X_test)
print("\nConfusion matrix (rows: real genuine/fraud, columns: predicted genuine/fraud):")
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred, target_names=["genuine", "fraud"], digits=2))
Output
always genuine  accuracy 97.0%  precision 0.0%  recall 0.0%  F1 0.00
logistic model  accuracy 84.3%  precision 16.1%  recall 100.0%  F1 0.28

Confusion matrix (rows: real genuine/fraud, columns: predicted genuine/fraud):
[[244  47]
 [  0   9]]
              precision    recall  f1-score   support

     genuine       1.00      0.84      0.91       291
       fraud       0.16      1.00      0.28         9

    accuracy                           0.84       300
   macro avg       0.58      0.92      0.59       300
weighted avg       0.97      0.84      0.89       300

The baseline wins on accuracy (97.0%) and catches no fraud at all. The model's accuracy is lower (84.3%), yet it catches all 9 frauds in the test set, at the cost of 47 false alarms (precision 16.1%). Whether that trade is good depends on the costs: if checking a flagged payment is cheap, it's a far better system than the baseline; if false alarms block real customers, you would raise the threshold and accept a lower recall. Accuracy alone would have picked the useless model.

Two things to read carefully:

  • The confusion matrix layout. scikit-learn puts the real classes in rows and the predictions in columns, in label order (0 = genuine first, then 1 = fraud). That's the opposite order to the table earlier in this lesson, so check the layout before reading the numbers.
  • The classification report gives precision, recall and F1 for every class. Support is how many real examples of each class the test set holds; with only 9 frauds, one more catch or miss moves recall by 11 points.

The scikit-learn metrics and scoring guide lists every metric and explains when each one fits.

Common mistakes

Practice exercise

Calculate precision and recall for a spam filter.

Your solutionPython
# A spam filter's results on a test set
true_positives = 30    # spam correctly caught
false_positives = 10   # good emails wrongly sent to spam
false_negatives = 20   # spam that got through

# Print precision and recall as percentages with one decimal, like:
# Precision: 12.3%
# Recall: 45.6%
Knowledge check

Only 1% of patients have a disease. A model predicts “healthy” for everyone. What is its accuracy?

Knowledge check

A model scores 97% accuracy on test data where 97% of the examples are negative. What should you check next?

Summary

  • Regression: MAE is the average size of errors; RMSE punishes big errors more.
  • Classification: the confusion matrix counts true and false positives and negatives.
  • Precision = how many flags were right; recall = how many positives were caught.
  • Accuracy can mislead on imbalanced data; choose the metric that matches the cost of each mistake.
  • In scikit-learn, sklearn.metrics computes them all (real labels first), and classification_report shows them per class. Always compare with a baseline.

Next: the steps every machine learning project follows.

Finished reading? Tick it off to track your progress.