Created
November 18, 2022 15:34
-
-
Save FreeFly19/87abb9ed285907c5477c864aa6988c29 to your computer and use it in GitHub Desktop.
F1 metric for keras
This file contains hidden or 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
import keras.backend as K | |
def f1(y_true, y_pred): | |
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))) | |
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) | |
precision = true_positives / (predicted_positives + K.epsilon()) | |
recall = true_positives / (possible_positives + K.epsilon()) | |
f1_val = 2*(precision*recall)/(precision+recall+K.epsilon()) | |
return f1_val | |
This file contains hidden or 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
# Add "f1" function to "metrics" parameter of "compile" method, example: | |
model.compile(optimizer = opt, loss = "categorical_crossentropy", metrics=["accuracy", f1]) | |
# pay attention "f1" is passed as a function not as a string compared to "accuracy". |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment