-
Notifications
You must be signed in to change notification settings - Fork 2
/
metrics.py
executable file
·72 lines (49 loc) · 1.75 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
""" Useful metrics to evaluate nnets in Keras.
@F. Comitani 2018-2022
"""
import tensorflow as tf
import keras
from keras import backend as K
def recall(y_true, y_pred):
"""Recall metric.
Only computes a batch-wise average of recall.
Computes the recall, a metric for multi-label classification of
how many relevant items are selected.
add axis=0 for macro f1
and return K.mean
Args:
y_true (array): array-like of ground truth labels.
y_pred (array): array-like of predicted labels.
Returns:
recall (float): recall score.
"""
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)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
Args:
y_true (array): array-like of ground truth labels.
y_pred (array): array-like of predicted labels.
Returns:
precision (float): precision score.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
def f1(y_true, y_pred):
"""MicroF1 score.
Args:
y_true (array): array-like of ground truth labels.
y_pred (array): array-like of predicted labels.
Returns:
(float): muF1 score.
"""
prec = precision(y_true, y_pred)
rec = recall(y_true, y_pred)
return 2*((prec*rec)/(prec+rec+K.epsilon()))