Search code examples
tensorflowkerasdeep-learningmetrics

AttributeError: module 'tensorflow.keras.metrics' has no attribute 'F1Score'


<< I already imported import tensorflow_addons as tfa when I am running the below code

    densenetmodelupdated.compile(loss ='categorical_crossentropy', optimizer=sgd_optimizer, metrics= 
      ['accuracy', tf.keras.metrics.Recall(),
                        tf.keras.metrics.Precision(),   
                        tf.keras.metrics.AUC(),
                        tfa.metrics.F1Score(num_classes=25, average="macro")]) 

<< it shows error

AttributeError                            Traceback (most recent call last)
<ipython-input-25-5f3ab8b4cc77> in <module>()
     16                         tf.keras.metrics.Precision(),
     17                         tf.keras.metrics.AUC(),
---> 18                         tfa.metrics.F1Score(num_classes=25, average="macro")])                        

AttributeError: module 'tensorflow.keras.metrics' has no attribute 'F1Score'

Solution

  • tensorflow_addons 0.16.0 with Tensorflow 2.7.0, tfa.metrics.F1Score works just fine.

    Working sample code

    import tensorflow_addons as tfa
    import numpy as np
    metric = tfa.metrics.F1Score(num_classes=3, threshold=0.5)
    y_true = np.array([[1, 1, 1],
                       [1, 0, 0],
                       [1, 1, 0]], np.int32)
    y_pred = np.array([[0.2, 0.6, 0.7],
                       [0.2, 0.6, 0.6],
                       [0.6, 0.8, 0.0]], np.float32)
    metric.update_state(y_true, y_pred)
    result = metric.result()
    result.numpy()
    

    Output

    array([0.5      , 0.8      , 0.6666667], dtype=float32)