-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFunctions.py
145 lines (115 loc) · 2.64 KB
/
Functions.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import numpy as np
def thresholder(x,tau):
""" Thresholding function
Args:
x (float or ndarray): a scalar
tau (float or ndarray): value b/w 0 and 1
Returns:
[float or ndarray]: 1 if x > tau, 0 if x <= tau
"""
assert tau>=0 and tau<=1, "tau not in [0,1]"
return np.round((np.sign(x-tau)+1)/2)
def rmse(x, xhat):
""" Root Mean Square Error
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[float or ndarray]: Root Mean Square Error
"""
if np.all(x == 0):
if np.all(xhat == 0):
return 0.
else:
return 1.
return np.linalg.norm(x - xhat) / np.linalg.norm(x)
def tp(x,xhat):
""" True Positive
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[int]: True Positive
"""
return np.sum(np.logical_and(x>0,xhat>0))
def fp(x, xhat):
""" False Positive
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[int]: False Positive
"""
return np.sum(np.logical_and(x==0,xhat>0))
def tn(x,xhat):
""" True negative
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[int]: True negative
"""
return np.sum(np.logical_and(x==0,xhat==0))
def fn(x, xhat):
""" False Negative
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[int]: False Negative
"""
return np.sum(np.logical_and(x>0,xhat==0))
def precision(x, xhat):
""" Precision, or positive predictive value
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[float]: Precision
"""
tp_ = tp(x,xhat)
fp_ = fp(x,xhat)
if tp_ + fp_ != 0:
precision = tp_ / (tp_ + fp_)
else:
precision = 1
return precision
def sensitivity(x, xhat):
""" Sensitivity, Recall, or true positive rate
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[float]: sensitivity
"""
tp_ = tp(x,xhat)
fn_ = fn(x,xhat)
if tp_ + fn_ != 0:
sensitivity = tp_ / (tp_ + fn_)
else:
sensitivity = 1
return sensitivity
def specificity(x, xhat):
""" Specificity, or True Negative rate
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[float]: Specificity
"""
tn_ = tn(x,xhat)
fp_ = fp(x,xhat)
if tn_ + fp_ != 0:
specificity = tn_ / (tn_ + fp_)
else:
specificity = 1
return specificity
def fpr(x,xhat):
""" False Positive rate
Args:
x (array_like): True value
xhat (array_like): Prediction
Returns:
[float]: False Positive rate
"""
return 1-specificity(x, xhat)