Skip to content
Discussion options

You must be logged in to vote

Have to cast y_true to float to match y_pred and then one-hot encode the predicted classes, and then you can calculate tp, fp, and fn
Here is the f1_score_metric function:

def f1_score_metric(y_true, y_pred):

    y_true = tf.cast(y_true, tf.float32)
    y_pred_classes = tf.argmax(y_pred, axis=-1)
    
    y_pred_one_hot = tf.one_hot(y_pred_classes, depth=num_classes)
    
    true_positives = tf.reduce_sum(y_true * y_pred_one_hot, axis=0)
    false_positives = tf.reduce_sum(y_pred_one_hot * (1 - y_true), axis=0)
    false_negatives = tf.reduce_sum((1 - y_pred_one_hot) * y_true, axis=0)
    
    precision = true_positives / (true_positives + false_positives + tf.keras.backend.epsilon())
 …

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by spacyuj
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants