Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Classification lessons
Evidence · ML-C01 · 12–18 MIN

Read a confusion matrix

Track which labels are confused.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeAdapt the Python
  3. TransferAdapt the Python

Understand the idea

Rows represent actual classes and columns predicted classes when using sklearn confusion_matrix. Explicit label order prevents accidental relabelling.

Track which labels are confused.Predicted classABActual AActual B7131B precision: 1 / 2B recall: 1 / 4Inspect every class; accuracy can hide missed cases.
Track which labels are confused.Scroll the diagram horizontally if needed.

What the syntax does

confusion_matrix
  • Counts actual/predicted class pairs; rows are actual classes and columns are predicted classes.
labels=['A','B']
  • Fixes both axis orders, including a class with zero predictions.

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
ERROR12 · all rows
actualpredicted
AA
AA
AA
AA
AA
AA
AA
AB
BA
BA
BA
BB
Your task
  1. Build the A/B confusion matrix from ERROR12.
answer
Hints

Think: Matrix rows and columns have different meanings and need an explicit class order.

Tools: confusion_matrix with labels.

Approach: Pass actual labels first, predictions second and supply the requested A/B order.

Explained solution
from sklearn.metrics import confusion_matrix
answer=confusion_matrix(df.actual,df.predicted,labels=['A','B'])

An explicit order keeps true-class and predicted-class counts interpretable even when frequencies differ.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.