-
Notifications
You must be signed in to change notification settings - Fork 1
/
metric.py
252 lines (207 loc) · 7.6 KB
/
metric.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""
Metrics for model and result evaluation
"""
import keras
import keras.backend as K
import numpy as np
#################################
# Model Metrics #
#################################
def batch_recall(y_true, y_pred):
"""Recall metric. THIS IS A REUSE OF REMOVED KERAS CODE:
https://github.com/keras-team/keras/commit/a56b1a55182acf061b1eb2e2c86b48193a0e88f7
Only computes a batchwise average of recall.
Computes the recall, a metric for multilabel classification of
how many relevant items are selected.
"""
true_positives = K.sum(
K.round(K.clip(y_true * y_pred, 0, 1))
)
possible_positives = K.sum(
K.round(K.clip(y_true, 0, 1))
)
return true_positives / (possible_positives + K.epsilon())
class BinaryRecall(keras.layers.Layer):
"""Stateful Metric to calculate the recall over all batches.
Assumes predictions and targets of shape `(samples, 1)`.
Reference:
https://github.com/keras-team/keras/blob/master/tests/keras/metrics_test.py
# Arguments
name: String, name for the metric.
"""
def __init__(self, name='global_recall', **kwargs):
super(BinaryRecall, self).__init__(name=name, **kwargs)
self.stateful = True
self.true_positives = K.variable(value=0, dtype='int32')
self.possible_positives = K.variable(value=0, dtype='int32')
def reset_states(self):
K.set_value(self.true_positives, 0)
K.set_value(self.possible_positives, 0)
def __call__(self, y_true, y_pred):
"""Computes the recall in a batch.
# Arguments
y_true: Tensor, batch_wise labels
y_pred: Tensor, batch_wise predictions
# Returns
The overall recall seen this epoch at the completion of the batch.
"""
y_true = K.cast(y_true, 'int32')
y_pred = K.cast(K.round(y_pred), 'int32')
true_pos = K.cast(K.sum(y_pred * y_true), 'int32')
poss_pos = K.cast(K.sum(y_true), 'int32')
self.add_update(
K.update_add(self.true_positives, true_pos),
inputs=[y_true, y_pred]
)
self.add_update(
K.update_add(self.possible_positives, poss_pos),
inputs=[y_true, y_pred]
)
true_pos = K.cast(self.true_positives * 1, "float32")
poss_pos = K.cast(self.possible_positives * 1, "float32")
return true_pos / (K.epsilon() + poss_pos)
class BinaryKappa(keras.layers.Layer):
"""Stateful Metric to calculate kappa over all batches.
Assumes predictions and targets of shape `(samples, 1)`.
Reference:
https://github.com/keras-team/keras/blob/master/tests/keras/metrics_test.py
# Arguments
name: String, name for the metric.
"""
def __init__(self, name='global_kappa', **kwargs):
super(BinaryKappa, self).__init__(name=name, **kwargs)
self.stateful = True
self.true_positives = K.variable(value=0, dtype='int32')
self.true_negative = K.variable(value=0, dtype='int32')
self.false_positives = K.variable(value=0, dtype='int32')
self.false_negative = K.variable(value=0, dtype='int32')
def reset_states(self):
K.set_value(self.true_positives, 0)
K.set_value(self.true_negative, 0)
K.set_value(self.false_positives, 0)
K.set_value(self.false_negative, 0)
def __call__(self, y_true, y_pred):
"""Computes the kappa in a batch.
# Arguments
y_true: Tensor, batch_wise labels
y_pred: Tensor, batch_wise predictions
# Returns
The kappa seen this epoch at the completion of the batch.
"""
y_true = K.cast(y_true, 'int32')
y_pred = K.cast(K.round(y_pred), 'int32')
true_pos = K.cast(
K.sum(y_pred * y_true),
'int32'
)
true_neg = K.cast(
K.sum((1 - y_pred) * (1 - y_true)),
'int32'
)
false_pos = K.cast(
K.sum(y_pred * (1 - y_true)),
'int32'
)
false_neg = K.cast(
K.sum((1 - y_pred) * y_true),
'int32'
)
self.add_update(
K.update_add(self.true_positives, true_pos),
inputs=[y_true, y_pred]
)
self.add_update(
K.update_add(self.true_negative, true_neg),
inputs=[y_true, y_pred]
)
self.add_update(
K.update_add(self.false_positives, false_pos),
inputs=[y_true, y_pred]
)
self.add_update(
K.update_add(self.false_negative, false_neg),
inputs=[y_true, y_pred]
)
true_pos = K.cast(self.true_positives * 1, "float32")
true_neg = K.cast(self.true_negative * 1, "float32")
false_pos = K.cast(self.false_positives * 1, "float32")
false_neg = K.cast(self.false_negative * 1, "float32")
sm = true_pos + true_neg + false_pos + false_neg
obs_agree = (true_pos + true_neg) / sm
poss_pos = (true_pos + false_neg) * (true_pos + false_pos) / (sm**2)
poss_neg = (true_neg + false_neg) * (true_neg + false_pos) / (sm**2)
poss_agree = poss_pos + poss_neg
return (obs_agree - poss_agree) / (1 - poss_agree + K.epsilon())
#################################
# Dataframe Metrics #
#################################
def basic_metrics(predict, label):
"""
Methods that returns:
true positive
true negative
false positive
false negative
Args:
predict: prediction
label: labels
Returns:
true_pos, true_neg, false_pos, false_neg, sum
"""
true_pos = int(sum(np.round(predict) * label))
true_neg = int(sum(-1 * np.round(predict - 1) * -1 * (label - 1)))
false_pos = int(sum(np.round(predict) * -1 * (label - 1)))
false_neg = int(sum((-1 * np.round(predict - 1) * label)))
sm = len(predict)
return true_pos, true_neg, false_pos, false_neg, sm
def kappa(predict, label):
"""
Methods for calculating Cohen's kappa.
https://en.wikipedia.org/wiki/Cohen%27s_kappa
Args:
predict: prediction
label: labels
Returns:
kappa
"""
true_pos, true_neg, false_pos, false_neg, sm = basic_metrics(predict, label)
obs_agree = (true_pos + true_neg) / sm
poss_pos = (true_pos + false_neg) * (true_pos + false_pos) / (sm ** 2)
poss_neg = (true_neg + false_neg) * (true_neg + false_pos) / (sm ** 2)
poss_agree = poss_pos + poss_neg
return (obs_agree - poss_agree) / (1 - poss_agree + np.finfo(np.float).eps)
def recall(predict, label):
"""
Methods for calculating recall.
https://en.wikipedia.org/wiki/Precision_and_recall
Args:
predict: prediction
label: labels
Returns:
recall
"""
true_pos, true_neg, false_pos, false_neg, sm = basic_metrics(predict, label)
return true_pos / (true_pos + false_neg + np.finfo(np.float).eps)
def precision(predict, label):
"""
Methods for calculating precision.
https://en.wikipedia.org/wiki/Precision_and_recall
Args:
predict: prediction
label: labels
Returns:
precision
"""
true_pos, true_neg, false_pos, false_neg, sm = basic_metrics(predict, label)
return true_pos / (true_pos + false_pos + np.finfo(np.float).eps)
def accuracy(predict, label):
"""
Methods for calculating accuracy.
Args:
predict: prediction
label: labels
Returns:
accuracy
"""
true_pos, true_neg, false_pos, false_neg, sm = basic_metrics(predict, label)
return (true_pos + true_neg) / (sm + np.finfo(np.float).eps)