-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmetrics.py
64 lines (48 loc) · 1.69 KB
/
metrics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import numpy as np
def accuracy(targets, predictions):
return np.equal(targets, predictions).mean()
def roc_сurve(y_true: np.ndarray[int], y_score: np.ndarray[float]):
# https://www.youtube.com/watch?v=4jRBRDbJemM
sorted_indices = np.argsort(y_score)[::-1]
y_true = y_true[sorted_indices]
y_score = y_score[sorted_indices]
tp = 0
fp = 0
tn = len(y_true) - np.sum(y_true)
fn = np.sum(y_true)
fpr = []
tpr = []
thresholds = []
for i in range(len(y_true)):
if y_true[i] == 1:
tp += 1
fn -= 1
else:
fp += 1
tn -= 1
fpr.append(fp / (fp + tn) if fp + tn > 0 else 0) #exception if all y_true are 1
tpr.append(tp / (tp + fn) if tp + fn > 0 else 0) #exception if all y_true are 0
thresholds.append(y_score[i])
return fpr, tpr, thresholds
def pr_curve(y_true: np.ndarray[int], y_score: np.ndarray[float]):
sorted_indices = np.argsort(y_score)[::-1]
y_true = y_true[sorted_indices]
y_score = y_score[sorted_indices]
tp = 0
fp = 0
fn = np.sum(y_true)
precision = []
recall = []
thresholds = []
for i in range(len(y_true)):
if y_true[i] == 1:
tp += 1
fn -= 1
else:
fp += 1
precision.append(tp / (tp + fp) if tp + fp > 0 else 0) #exception if all y_true are 0
recall.append(tp / (tp + fn) if tp + fn > 0 else 0) #exception if all y_true are 1
thresholds.append(y_score[i])
return precision, recall, thresholds
def auc(x: np.ndarray[float], y: np.ndarray[float]):
return np.trapz(y, x)