Accuracy, Precision, Recall and F1
def score(targets, predictions):
tp, tn, fp, fn = 0, 0, 0, 0
for target, prediction in zip(targets, predictions):
if target == 1:
if prediction ==1:
tp += 1
else:
fn += 1
else:
if prediction ==1:
fp += 1
else:
tn += 1
a = (tp+tn) / (tp+tn +fp +fn)
r = tp / (tp + fn)
p = tp / (tp + fp)
f1 = 2 * (p*r)/(p+r)
return a, r, p, f1
import torch # since I use PyTorch as my DL library!
def scorepro(targets, predictions):
total = len(targets)
true_positives = sum(torch.multiply(targets, predictions)) # tp
possible_positives= sum(targets) # tp + fn
predicted_positives = sum(predictions) # tp + fp
acc = sum(targets==predictions) / total
recall = true_positives / possible_positives
precision = true_positives / predicted_positives
f1 = 2*((precision*recall)/(precision+recall))
return acc.item(), recall.item(), precision.item(), f1.item()
Testing:
targ = [0, 1, 0, 1]
pred = [0, 1, 1, 0]
targt = torch.Tensor(targ)
predt = torch.Tensor(pred)
score(targt, predt) # (0.5, 0.5, 0.5, 0.5)
scorepro(targt, predt) # (0.5, 0.5, 0.5, 0.5)