Artificial Intelligence Fundamentals / Learn From Labelled Data

Choose a classification metric

Lesson 11 of 26. Open to read. No account needed.

Not All Mistakes Cost the Same

The baseline lesson showed that accuracy can hide a model that finds nothing. The deeper problem is that accuracy counts every mistake the same, while in practice they rarely cost the same. A screening test that misses a serious illness does far more harm than one that sends a healthy person for a second test. A fraud system that blocks honest customers' payments causes a different harm from one that lets fraud through.

To choose a model sensibly, you need to see which mistakes it makes and choose a measure that matches what those mistakes cost. This lesson covers the two-class case, where one class is the positive class, the thing you are looking for, such as fraud or a fault, and the other is negative.

The Confusion Matrix

A confusion matrix counts every combination of true class and predicted class. In scikit-learn, the entry in row i and column j is the number of samples whose true class is i and whose predicted class is j. With classes 0 (negative) and 1 (positive), the four cells have names:

A two-by-two confusion matrix. Rows are true classes, columns are predicted classes. Top left: true negatives, 279, real negatives predicted negative. Top right: false positives, 5, real negatives predicted positive. Bottom left: false negatives, 8, real positives that were missed. Bottom right: true positives, 8, real positives that were found. Precision uses the right-hand column: 8 divided by 13. Recall uses the bottom row: 8 divided by 16.

Read the diagram row by row. Each row is what really happened; each column is what the model said. The diagonal from top left to bottom right holds the correct predictions. The other two cells are the two kinds of mistake: false positives, false alarms, and false negatives, misses. Precision looks down the right-hand column; recall looks along the bottom row.

Precision and Recall

  • Precision = true positives ÷ (true positives + false positives). Of the cases the model flagged, how many were really positive? Low precision means many false alarms.
  • Recall = true positives ÷ (true positives + false negatives). Of the cases that were positive, how many did the model find? Low recall means many misses.

Both range from 0 to 1. They usually pull against each other: flagging more cases finds more real positives, raising recall, but adds false alarms, lowering precision. Which matters more depends on the costs:

If this mistake is worsePrioritiseExample
Missing a real positiveRecallScreening for a serious illness, followed by a confirmatory test
Raising a false alarmPrecisionAutomatically blocking payments with no human review

When no sample is predicted positive, precision divides zero by zero. Then scikit-learn returns 0.0 and prints an UndefinedMetricWarning. Passing zero_division=0 states that you accept 0.0 and silences the warning.

Exercise: Choose a Metric

You will evaluate a classifier on imbalanced generated data, compare its metrics with the baseline's, and check the calculations by hand.

Starting state: the course environment, active in your terminal. The script generates its own data.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/metric-choice
    cd ~/ai-practice/metric-choice
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\metric-choice
    cd $HOME\ai-practice\metric-choice
    

    Save this as metric_choice.py in that folder:

    """Evaluate a classifier on imbalanced data with a confusion matrix, precision and recall."""
    from sklearn.datasets import make_classification
    from sklearn.dummy import DummyClassifier
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score
    from sklearn.model_selection import train_test_split
    
    X, y = make_classification(n_samples=1000, weights=[0.95], random_state=2)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2, stratify=y)
    
    model = LogisticRegression().fit(X_train, y_train)
    predictions = model.predict(X_test)
    print("Confusion matrix (rows: true class 0, 1; columns: predicted 0, 1):")
    print(confusion_matrix(y_test, predictions))
    print("Accuracy: ", round(accuracy_score(y_test, predictions), 3))
    print("Precision:", round(precision_score(y_test, predictions), 3))
    print("Recall:   ", round(recall_score(y_test, predictions), 3))
    
    baseline_predictions = DummyClassifier().fit(X_train, y_train).predict(X_test)
    print("Baseline accuracy: ", round(accuracy_score(y_test, baseline_predictions), 3))
    print("Baseline precision:", precision_score(y_test, baseline_predictions, zero_division=0))
    print("Baseline recall:   ", recall_score(y_test, baseline_predictions))
    
  2. Run it:

    python metric_choice.py
    

    Output, which should match exactly:

    Confusion matrix (rows: true class 0, 1; columns: predicted 0, 1):
    [[279   5]
     [  8   8]]
    Accuracy:  0.957
    Precision: 0.615
    Recall:    0.5
    Baseline accuracy:  0.947
    Baseline precision: 0.0
    Baseline recall:    0.0
    
  3. Before reading on, calculate precision and recall yourself from the matrix, using the formulas above, and compare with the printed values.

How the Script Works and What It Shows

The data and model. The data is the imbalanced generated set from the baseline lesson, about 5% positive, split with a 0.3 test share: 300 test samples, 16 of them positive. A logistic regression model is trained and its test predictions stored in predictions.

The matrix. confusion_matrix(y_test, predictions) takes the true labels first and the predictions second. Of 284 real negatives, 279 were predicted negative and 5 positive. Of 16 real positives, 8 were missed and 8 found.

The scores. Accuracy is (279 + 8) ÷ 300 = 0.957, only one point above the baseline's 0.947. Precision is 8 ÷ (8 + 5) = 0.615: about six in ten flagged cases were real. Recall is 8 ÷ (8 + 8) = 0.5: half the real positives were missed. The baseline flags nothing, so its precision is undefined, reported as 0.0 because of zero_division=0, and its recall is 0.0.

So accuracy says the model is barely better than doing nothing, while recall shows it finds half the positives and the baseline none. Whether finding half is good enough depends on what a miss costs.

If you removed zero_division=0 from the baseline line, the result would still be 0.0, but scikit-learn would also print an UndefinedMetricWarning explaining that precision is ill-defined because nothing was predicted positive.

Success: your hand calculations match the printed precision and recall, and you can explain why accuracy barely separates the model from the baseline while recall does.

If something differs:

What you seeLikely causeNext step
The matrix looks flipped, with large numbers bottom rightThe arguments to confusion_matrix were swapped, or the classes are labelled differentlyPass y_test first, then predictions
UndefinedMetricWarning appearszero_division=0 was left out of the baseline precision lineAdd it back, or accept the warning
Different numberstest_size, random_state or weights was changedRestore the values shown
ModuleNotFoundErrorThe course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf metric-choice
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse metric-choice
    ls
    

    Check that the first ls shows metric-choice before removing it.

Independent task: two models check 1,000 bridge cables, 40 of which are damaged. Every flagged cable is then inspected by an engineer; an unflagged damaged cable is not inspected at all. Calculate each model's precision and recall, and choose one.

Model A                     Model B
[[916  44]                  [[954   6]
 [  4  36]]                  [ 16  24]]

Check Your Understanding

For each task, choose whether precision or recall matters more, and explain using the cost of each kind of mistake:

  1. A screening test for a serious, treatable condition, where every positive result is followed by a reliable confirmatory test.
  2. A system that automatically suspends customer accounts for suspected fraud, with no human check.

Answer and Reasoning

Independent task

  • Model A: recall = 36 ÷ (36 + 4) = 0.9; precision = 36 ÷ (36 + 44) = 0.45.
  • Model B: recall = 24 ÷ (24 + 16) = 0.6; precision = 24 ÷ (24 + 6) = 0.8.

Choose model A. A missed damaged cable is never inspected, which could be dangerous, while a false alarm costs only an engineer's inspection. Model A misses 4 damaged cables against model B's 16, at the price of 44 unnecessary inspections instead of 6. The rows are the true classes, so the damaged cables are the bottom row in both matrices.

Understanding check

  1. Recall. A missed case goes untreated, while a false alarm is caught by the confirmatory test at the cost of some worry and an extra test.
  2. Precision. Every false positive suspends an honest customer with no one to catch the mistake, so false alarms are costly. Even then, the stakes argue for adding human review rather than relying on any single metric.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy