Introduction to NumPy and Matplotlib
Chapter 6: NumPy functions
Exercise - Computing accuracy
Let’s do one more task!
Here is our confusion matrix again.
apple | orange | pear | |
---|---|---|---|
apple | 18 | 3 | 9 |
orange | 1 | 30 | 4 |
pear | 7 | 5 | 23 |
For a Machine Learning classification task, we might have to compute an evaluation metric called
Your task
Use NumPy
to compute the accuracy from the confusion matrix above.
As hinted in the equation, you will need the compute:
- the total number of correct predictions
- the total number of instances
- divide (1) by (2)
Implement this in NumPy
. It can be done in a single line if you wish!
import numpy as np
x = np.array([[18, 3, 9], [1, 30, 4], [7, 5, 23]])
accuracy = ????
assert accuracy == 0.71
Possible solutions:
accuracy = x.diagonal().sum() / x.sum()
accuracy = np.sum(np.diagonal(x)) / np.sum(x)