-
Notifications
You must be signed in to change notification settings - Fork 15
/
metrics.py
executable file
·73 lines (59 loc) · 2.71 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
65
66
67
68
69
70
71
72
73
import tensorflow as tf
from sklearn.metrics import accuracy_score
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss)
def masked_accuracy(preds, labels, mask):
"""Accuracy with masking."""
# correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1))
# accuracy_all = tf.cast(correct_prediction, tf.float32)
# mask = tf.cast(mask, dtype=tf.float32)
# mask /= tf.reduce_mean(mask)
# accuracy_all *= mask
# return tf.reduce_mean(accuracy_all)
correct_prediction = tf.equal(labels>=0.5,preds>=0.5)
accuracy_all = tf.cast(correct_prediction, tf.float32)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
accuracy_all *= mask
return tf.reduce_mean(accuracy_all)
def masked_bilinearsigmoid_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
maskIndex = tf.where(mask>0)
maskIndex = tf.cast(maskIndex, dtype=tf.int32)
maskedPreds = tf.gather_nd(preds, maskIndex)
maskedLabels = tf.gather_nd(labels, maskIndex)
loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=maskedPreds, targets=maskedLabels)
return tf.reduce_mean(loss)
def masked_squreloss(preds, labels, mask):
# maskIndex = tf.where(mask>0)
# maskIndex = tf.cast(maskIndex, dtype=tf.int32)
# maskedPreds = tf.gather_nd(preds, maskIndex)
# maskedLabels = tf.gather_nd(labels, maskIndex)
# loss = tf.squared_difference(maskedPreds,maskedLabels)
# return tf.reduce_mean(loss)
loss = tf.squared_difference(preds,labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss)
def masked_bilinearsoftmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
maskIndex = tf.where(mask>0)
maskIndex = tf.cast(maskIndex, dtype=tf.int32)
maskedPreds = tf.gather_nd(preds, maskIndex)
maskedLabels = tf.gather_nd(labels, maskIndex)
loss = tf.nn.softmax_cross_entropy_with_logits(logits=maskedPreds, labels=maskedLabels)
return tf.reduce_mean(loss)
def masked_bilinear_accuray(preds, labels, mask):
maskIndex = tf.where(mask > 0)
maskIndex = tf.cast(maskIndex, dtype=tf.int32)
maskedPreds = tf.gather_nd(preds, maskIndex)
maskedLabels = tf.gather_nd(labels, maskIndex)
correct_prediction = tf.equal(maskedLabels >= 0.5, maskedPreds >= 0.5)
accuracy_all = tf.cast(correct_prediction, tf.float32)
return tf.reduce_mean(accuracy_all)