Chapter 6: NumPy functions

Exercise - Computing accuracy

face Josiah Wang

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 accuracy.

accuracy = \frac{| correct |}{| instances |}

Your task

Use NumPy to compute the accuracy from the confusion matrix above.

As hinted in the equation, you will need the compute:

  1. the total number of correct predictions
  2. the total number of instances
  3. 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)