Here’s how to compute true positives, false positives, true negatives, and false negatives in Python using the Numpy library.

Note that we are assuming a binary classification problem here. That is a value of `1`

indicates a **positive** class, and a value of `0`

indicates a **negative** class. For *multi-class* problems, this doesn’t really hold.

So let’s start by setting up an example scenario where we predicted 7 binary (0 or 1) labels, and are given the true binary labels.

# Use the numpy library.
import numpy as np
# These are the labels we predicted.
pred_labels = np.asarray([0,1,1,0,1,0,0])
print 'pred labels:\t\t', pred_labels
# These are the true labels.
true_labels = np.asarray([0,0,1,0,0,1,0])
print 'true labels:\t\t', true_labels |

# Use the numpy library.
import numpy as np# These are the labels we predicted.
pred_labels = np.asarray([0,1,1,0,1,0,0])
print 'pred labels:\t\t', pred_labels# These are the true labels.
true_labels = np.asarray([0,0,1,0,0,1,0])
print 'true labels:\t\t', true_labels

pred labels: [0 1 1 0 1 0 0]
true labels: [0 0 1 0 0 1 0]

Here’s the quick way to compute true/false positives and true/false negatives. Basically we will,

- find the predicted and true labels that are assigned to some specific class
- use the “AND” operator to combine the results into a single binary vector
- sum over the binary vector to count how many incidences there are

# True Positive (TP): we predict a label of 1 (positive), and the true label is 1.
TP = np.sum(np.logical_and(pred_labels == 1, true_labels == 1))
# True Negative (TN): we predict a label of 0 (negative), and the true label is 0.
TN = np.sum(np.logical_and(pred_labels == 0, true_labels == 0))
# False Positive (FP): we predict a label of 1 (positive), but the true label is 0.
FP = np.sum(np.logical_and(pred_labels == 1, true_labels == 0))
# False Negative (FN): we predict a label of 0 (negative), but the true label is 1.
FN = np.sum(np.logical_and(pred_labels == 0, true_labels == 1))
print 'TP: %i, FP: %i, TN: %i, FN: %i' % (TP,FP,TN,FN) |

# True Positive (TP): we predict a label of 1 (positive), and the true label is 1.
TP = np.sum(np.logical_and(pred_labels == 1, true_labels == 1))# True Negative (TN): we predict a label of 0 (negative), and the true label is 0.
TN = np.sum(np.logical_and(pred_labels == 0, true_labels == 0))# False Positive (FP): we predict a label of 1 (positive), but the true label is 0.
FP = np.sum(np.logical_and(pred_labels == 1, true_labels == 0))# False Negative (FN): we predict a label of 0 (negative), but the true label is 1.
FN = np.sum(np.logical_and(pred_labels == 0, true_labels == 1))print 'TP: %i, FP: %i, TN: %i, FN: %i' % (TP,FP,TN,FN)

TP: 1, FP: 2, TN: 3, FN: 1

There you go! If you want a more detailed explanation, I wrote a much longer example using a Jupyter notebook you can look at here:

https://github.com/jeremykawahara/tutorials/blob/master/how_to_compute_true_false_positivies_and_true_false_negatives.ipynb

*Related*