Skip to content

Instantly share code, notes, and snippets.

@FreeFly19
Created November 18, 2022 15:34
Show Gist options
  • Save FreeFly19/87abb9ed285907c5477c864aa6988c29 to your computer and use it in GitHub Desktop.
Save FreeFly19/87abb9ed285907c5477c864aa6988c29 to your computer and use it in GitHub Desktop.
F1 metric for keras
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
# 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