Last active
November 9, 2018 03:15
-
-
Save applenob/0bd0e099e4e1baad51cfd702c9dd86ad to your computer and use it in GitHub Desktop.
F1 metric for keras.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Reference: https://stackoverflow.com/questions/43547402/how-to-calculate-f1-macro-in-keras""" | |
from keras import backend as K | |
def f1(y_true, y_pred): | |
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. | |
""" | |
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. | |
""" | |
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 | |
precision = precision(y_true, y_pred) | |
recall = recall(y_true, y_pred) | |
return 2*((precision*recall)/(precision+recall+K.epsilon())) | |
# Usage | |
# model.compile(loss='binary_crossentropy', | |
# optimizer='adam', | |
# metrics=['accuracy', f1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment