David
David

Reputation: 433

Compute precision and accuracy using numpy

Suppose two lists true_values = [1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0] and predictions = [1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0]. How can I compute the accuracy and the precision using numpy?

enter image description here

Upvotes: 3

Views: 23306

Answers (4)

Thomas
Thomas

Reputation: 17422

If you really want to calculate it yourself instead of using a library like in Quang Hoang's answer, just count the number of (true|false) (positives|negatives) and plug the values into your formula:

tp = 0
tn = 0
fp = 0
fn = 0

for t,p in zip(true_values, predictions):
   if t == p:
       if p == 1:
           tp += 1
       else:
           tn += 1
   else:
       if p == 1:
           fn += 1
       else:
           fp += 1

accuracy = (tp + tn) / (tp + tn + fp + fn)
precision = tp / (tp + fp)

This wikipedia article has a nice info box with formulas that use exactly these values.

Upvotes: 0

Nicolas Gervais
Nicolas Gervais

Reputation: 36624

I'm only going to answer for precision, because I posted a duplicate for accuracy and there should be one question per thread:

sum(map(lambda x, y: x == y == 1, true_values, predictions))/sum(true_values)
0.5

Use np.sum if you absolutely want to use Numpy

Here is for the mean:

np.equal(true_values, predictions).mean()

Upvotes: 0

ymentha14
ymentha14

Reputation: 499

import numpy as np

true_values = np.array([[1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0]])
predictions = np.array([[1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0]])

N = true_values.shape[1]
accuracy = (true_values == predictions).sum() / N
TP = ((predictions == 1) & (true_values == 1)).sum()
FP = ((predictions == 1) & (true_values == 0)).sum()
precision = TP / (TP+FP)

This is the most concise way I came up with (assuming no sklearn), there might be even shorter though!

Upvotes: 13

Quang Hoang
Quang Hoang

Reputation: 150745

This is what sklearn, which uses numpy behind the curtain, is for:

from sklearn.metrics import precision_score, accuracy_score

accuracy_score(true_values, predictions), precision_score(true_values, predictions)

Output:

(0.3333333333333333, 0.375)

Upvotes: 1

Related Questions