Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course

4.2 Evaluating Models: Confusion Matrix, Metrics and Hyperparameter Tuning

Unit 4 – Data and Analysis · 90 min read · 9 MCQs to check yourself

StatQuest – machine learning fundamentals: the confusion matrix

1. Classification metrics

Cell Meaning (disease test example)
TP – true positive sick person correctly predicted sick
TN – true negative healthy person correctly predicted healthy
FP – false positive healthy person wrongly predicted sick (false alarm)
FN – false negative sick person wrongly predicted healthy (missed case)
Metric Formula Question it answers
Accuracy (TP + TN) / total What fraction of all predictions are correct?
Precision TP / (TP + FP) When the model says “positive”, how often is it right?
Recall (sensitivity) TP / (TP + FN) Of all real positives, how many did it find?
F1-score 2 × P × R / (P + R) Balance of precision and recall

Worked example (model paper): TP = 90, FN = 10, FP = 30, TN = 70 (total 200).

TP, FN, FP, TN = 90, 10, 30, 70
accuracy  = (TP + TN) / (TP + TN + FP + FN)
precision = TP / (TP + FP)
recall    = TP / (TP + FN)
f1 = 2 * precision * recall / (precision + recall)
print(f"accuracy={accuracy:.0%} precision={precision:.0%} recall={recall:.0%} F1={f1:.3f}")

Output:

accuracy=80% precision=75% recall=90% F1=0.818

Which metric matters? (situations)

Situation Most important Why
Cancer screening Recall Missing a sick patient (FN) is dangerous
Spam filter Precision Sending an important e-mail to spam (FP) is harmful
Fraud detection (1 fraud in 1,000) Recall / F1, not accuracy A model that says “no fraud” always is 99.9% accurate but useless
Balanced classes, equal costs Accuracy Simple and fair

2. Regression metrics

Metric Meaning
MAE (mean absolute error) average size of the errors, in the same unit (e.g. marks)
RMSE (root mean squared error) like MAE but punishes large errors more
R² proportion of variation explained (1 = perfect, 0 = no better than the average)

3. Overfitting and underfitting

4. Hyperparameter tuning

Parameters are learned from data (e.g. the slope of a line). Hyperparameters are settings chosen before training: max_depth of a decision tree, k in KNN, learning rate and number of layers in a neural network. Tuning tries different values and keeps the one that scores best on validation data (often with cross-validation or a grid search).

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)
for depth in [1, 2, 3, 5]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_tr, y_tr)
    print(f"max_depth={depth}: train={tree.score(X_tr, y_tr):.2f} test={tree.score(X_te, y_te):.2f}")

best = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_tr, y_tr)
names = ["sepal length", "sepal width", "petal length", "petal width"]
for name, imp in sorted(zip(names, best.feature_importances_), key=lambda p: -p[1]):
    print(f"{name:13} importance {imp:.2f}")

Output:

max_depth=1: train=0.70 test=0.60
max_depth=2: train=0.96 test=0.91
max_depth=3: train=0.98 test=0.98
max_depth=5: train=1.00 test=0.98
petal width   importance 0.58
petal length  importance 0.42
sepal length  importance 0.00
sepal width   importance 0.00

Interpreting the output: depth 1 underfits; depth 3 gives the best test score, so we choose it. Feature importance shows that petal measurements have the most impact on the prediction – useful for explaining the model and for feature selection.

5. Ways to improve a model

More and better-quality data · better features · tune hyperparameters · try a different algorithm · balance classes · regularisation to reduce overfitting · ensemble methods (random forest).

Short and long questions

1. A hospital builds a model to detect diabetes. On 500 test patients: 80 diabetic patients were correctly detected, 20 diabetic patients were missed, 40 healthy patients were wrongly flagged and 360 healthy patients were correctly cleared. (a) Draw the confusion matrix. (b) Calculate accuracy, precision, recall and F1. (c) Which metric matters most here and how could the model be improved? (1 + 3 + 2)

Model answer

(a) (1)

Predicted diabetic Predicted healthy
Actual diabetic TP = 80 FN = 20
Actual healthy FP = 40 TN = 360

(b) (3)

  • Accuracy = (80 + 360) / 500 = 0.88 = 88%
  • Precision = 80 / (80 + 40) = 0.667 ≈ 66.7%
  • Recall = 80 / (80 + 20) = 0.80 = 80%
  • F1 = 2 × 0.667 × 0.80 / (0.667 + 0.80) ≈ 0.727

(c) (2) Recall matters most: a missed diabetic patient (FN) goes untreated, while a false alarm only needs a confirmation test. Improve by: lowering the decision threshold to catch more positives, collecting more data on diabetic patients (class balance), engineering better features (BMI, glucose history), and hyperparameter tuning with cross-validation, then re-checking recall on unseen data.

2. A model has precision 0.8 and recall 0.6. Calculate its F1-score and explain what it means.

Model answer

F1 = 2 × 0.8 × 0.6 / (0.8 + 0.6) = 0.96 / 1.4 = 0.686 (≈ 68.6%). It is a single score balancing precision and recall; it is pulled towards the lower value (recall), showing that the model misses many positives.

3. Why is accuracy not a good metric for a fraud-detection model? Which metric would you use?

Model answer

Fraud is rare (e.g. 1 in 1,000). A model that always predicts “not fraud” is 99.9% accurate but catches no fraud. Use recall (how many frauds are caught) together with precision or the F1-score.

4. What is hyperparameter tuning? Give two examples of hyperparameters.

Model answer

Hyperparameters are settings chosen before training (not learned from data). Tuning tries different values (grid search, cross-validation) and keeps those giving the best validation performance. Examples: max_depth of a decision tree; k in K-nearest neighbours; learning rate / number of layers of a neural network.

5. Explain overfitting and underfitting. How can each be detected?

Model answer
  • Overfitting: the model learns noise and details of the training data – high training score, low test score. Fix: more data, simpler model, regularisation, tune hyperparameters.
  • Underfitting: the model is too simple to capture the pattern – low scores on both training and test data. Fix: more complex model, better features. Detection: compare training and test (validation) scores.

6. Calculate accuracy, precision and recall for a model with TP = 90, FN = 10, FP = 30 and TN = 70.

Model answer

Total = 200.

  • Accuracy = (TP + TN) / total = (90 + 70) / 200 = 0.80 = 80%
  • Precision = TP / (TP + FP) = 90 / 120 = 0.75 = 75%
  • Recall = TP / (TP + FN) = 90 / 100 = 0.90 = 90%

This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: 4.1 Machine Learning Basics: Learning from Data, Features and Train-Test Split · Next: 4.3 Data Visualisation and Data Storytelling with SQL and Python

All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course