AI & Machine Learning Master Course — 061. Confusion matrices and error accounting
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 061: Confusion matrices and error accounting
Prerequisites: Lesson 060. Learning outcome: Calculate and interpret class-specific confusion-matrix quantities.
1. Start with counts before summaries
A confusion matrix records how true labels and predicted labels coincide. It is an accounting table, not a model itself. Before computing a score, define the evaluation population, observation unit, label mapping, and decision rule. A matrix for tickets differs from one for conversations if several tickets belong to the same conversation.
In scikit-learn's convention, rows are true classes and columns are predicted classes. Other presentations may transpose those axes, so label them explicitly rather than recognizing a familiar-looking grid and assuming its orientation. The diagonal contains correct class decisions; off-diagonal cells describe specific confusions.
2. Read binary errors with the positive event fixed
For class order negative,positive, the first row contains true negatives and false positives; the second contains false negatives and true positives. A false positive predicts the positive event when it did not occur. A false negative misses an event that did occur. Neither name determines which error is more costly without task context.
A parcel inspection system can label damage positive, while another analysis may focus on safe parcels as positive. Reversing the event changes the names and denominators of the derived quantities. Include a plain-language outcome definition beside the matrix, especially when numerical labels have no natural meaning.
The four cells should sum to the number of evaluated observations when every row has one known true label and one prediction. Missing labels, abstentions, filtered cases, or sample weights require extra accounting. A weighted matrix may contain noninteger totals and should not be described as raw case counts.
3. Extend accounting to several classes
The example uses three classes with matrix[[3, 2, 0],[1, 1, 1],[0, 1, 1]]. Row totals are five,three,two, so those are the true class supports. Column totals are four,four,two, describing predicted workload. Five of ten observations lie on the diagonal, giving accuracy 0.5.
For class 2 considered against all other classes, true positives are the bottom-right cell, one. False negatives are the remaining cells in its row, one. False positives are the remaining cells in its column, one. True negatives are all cells outside its row and column, seven. This produces a binary matrix[[7, 1],[1, 1]].
One-versus-rest matrices are related views of the same observations, not separate independent datasets. In single-label multiclass classification, each wrong prediction contributes a false negative to its true class and a false positive to its predicted class. Summing such errors requires attention to what is being counted; adding every per-class error count can count the same mistake twice.
4. Normalization changes the question
Row normalization divides each cell by its true-class support. It asks where observations from a given true class were sent. The diagonal gives class recall. In the example, class 0 recall is 3/5=0.6. Its row shows that 40% of true class 0 observations were predicted class 1.
Column normalization divides by predicted-class totals. It asks what actually happened among observations receiving a particular prediction. The class 0 diagonal becomes 3/4=0.75, its precision. The same diagonal count therefore yields different fractions because the denominators answer different questions.
Normalizing by the full total instead shows each joint outcome's share of the evaluation sample. Keep raw counts alongside normalized views. A cell labeled 50% could represent one of two observations or five thousand of ten thousand; those provide very different evidence about stable performance.
![Three aligned matrices use true classes as rows and predictions as columns, in order 0, 1, 2. Raw counts are [[3, 2, 0], [1, 1, 1], [0, 1, 1]], with row totals 5, 3, 2 and column totals 4, 4, 2. Row and column normalization turn class 0’s diagonal count 3 into recall 0.60 and precision 0.75. Values are rounded to two decimals; accuracy is 0.50.](https://smartyfy.mrindigi.com/wp-content/uploads/2026/10/aiml-061-confusion-matrix-normalization-denominators.png)
5. Keep exclusions and actions visible
A review action is not automatically another true class. If the system can abstain, report action counts and the cases remaining for automatic decisions. A high accuracy after excluding all difficult reviewed cases describes selective performance and should be accompanied by coverage, review workload, and the rule that produced the selection.
Fix the label list when comparing matrices across models or folds. A rare absent class should not silently reorder axes. If an API selects only a subset of labels, the resulting matrix may no longer account for every observation; verify its total and describe the selection. Also preserve identifiers so a surprising cell can be traced to examples without losing privacy controls.
A matrix ignores probability quality and ranking within a class decision. Two models can have the same matrix but very different confidence estimates. Use it as a transparent foundation for error analysis, alongside other diagnostics rather than as a complete evaluation report.
CPU lab: reconcile every denominator
The script uses NumPy and scikit-learn locally, checked with versions 2.3.5 and 1.8.0. It constructs ten invented labels and predictions, then prints raw, row-normalized, and column-normalized matrices with an explicit class order. No model fitting or outside dataset is involved.
Assertions verify that the raw matrix totals ten and that diagonal count divided by total equals accuracy. The final output independently constructs class 2's one-versus-rest view. These checks are valuable because an axis or label-order error can make otherwise correct metric formulas describe the wrong operational event.
import numpy as np
from sklearn.metrics import confusion_matrix,multilabel_confusion_matrix,accuracy_score
y=np.array([0,0,0,0,0,1,1,1,2,2])
p=np.array([0,0,0,1,1,0,1,2,1,2])
C=confusion_matrix(y,p,labels=[0,1,2])
print('Counts:',C.tolist())
print('Row normalized:',confusion_matrix(y,p,labels=[0,1,2],normalize='true').round(4).tolist())
print('Column normalized:',confusion_matrix(y,p,labels=[0,1,2],normalize='pred').round(4).tolist())
assert C.sum()==len(y)
assert np.isclose(np.trace(C)/C.sum(),accuracy_score(y,p))
print('Accuracy:',accuracy_score(y,p))
print('One-versus-rest class2:',multilabel_confusion_matrix(y,p,labels=[0,1,2])[2].tolist())
Four practice questions with worked answers
Practice 1
From the example matrix, calculate class 1 support, predicted count, recall, and precision.
Answer: The class 1 row sums to 3 and its column to 4. Its true-positive cell is 1, so recall is 1/3≈0.3333 and precision 1/4=0.25. Support counts true class 1 cases; predicted count describes how many cases the system routes to class 1.
Practice 2
Why does the class 2 one-versus-rest true-negative count equal seven?
Answer: Exclude class 2’s row and column and add the remaining four cells:3+2+1+1=7. These cases are neither truly class 2 nor predicted class 2. Some may still be wrong between classes 0 and 1, so a true negative in this binary view need not be a correct multiclass decision.
Practice 3
A model reviews 30 of 100 cases and correctly classifies 63 of the remaining 70. What should accompany its 90% selective accuracy?
Answer: Report automatic coverage 70/100=70%, review fraction 30%, the review policy, and outcomes or costs for reviewed cases where available. The 90% figure describes only automatically decided observations; it must not be presented as 90 correct predictions across all 100 cases.
Practice 4
A normalized cell equals 0.5 in two evaluation slices, with supports 2 and 2000. What information is missing if counts are omitted?
Answer: The amount of evidence differs enormously. One case out of two and one thousand out of two thousand share a proportion but not precision of estimation. Report numerator, denominator, sampling design, and appropriate uncertainty before treating the rates as equally stable.
Five multiple-choice questions
Question 1
In the stated matrix convention, what do rows represent?
- A. Probability bins
- B. True classes
- C. Predicted classes
Correct: B. Columns represent predictions; labeling both axes avoids transposition mistakes.
Question 2
What does row-normalized diagonal entry measure?
- A. Recall for that true class
- B. Precision for that predicted class
- C. Overall accuracy regardless of row
Correct: A. Its denominator is the true-class row total.
Question 3
Can a one-versus-rest true negative still be a wrong multiclass prediction?
- A. No, true negative always means fully correct
- B. Only when probabilities are missing
- C. Yes, it may confuse two other classes
Correct: C. The binary view asks only whether the selected class was involved.
Question 4
Why retain raw counts with percentages?
- A. To make normalization unnecessary in every case
- B. To reveal support and reconcile totals
- C. To guarantee causal interpretation
Correct: B. Denominators determine evidential strength and clarify the question each percentage answers.
Question 5
What does a confusion matrix omit?
- A. The number of correct class decisions
- B. The distribution of predicted labels
- C. Probability calibration and within-class ranking
Correct: C. Thresholded counts lose information contained in continuous scores and probabilities.
Common pitfalls
Do not assume axis orientation or label order. Do not hide unknown labels, excluded rows, or review decisions. Avoid adding one-versus-rest error counts without noticing duplicated accounting, and never interpret a percentage without its denominator.
Summary
Confusion matrices make class errors auditable. Fix the event definitions and axes, reconcile totals, distinguish row and column normalization, and retain support counts. Report abstention and probability diagnostics separately so the table remains an honest view of the system.