AttributeError:模块“tensorflow.keras.metrics”没有属性“F1Score”

Bal*_*sha 3 metrics deep-learning keras tensorflow

<< 当我运行下面的代码时,我已经导入了 import tensorflow_addons as tfa

    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")]) 
Run Code Online (Sandbox Code Playgroud)

<<显示错误

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'
Run Code Online (Sandbox Code Playgroud)

小智 6

tensorflow_addons 0.16.0 与 Tensorflow 2.7.0 一起tfa.metrics.F1Score工作得很好。

工作示例代码

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()
Run Code Online (Sandbox Code Playgroud)

输出

array([0.5      , 0.8      , 0.6666667], dtype=float32)
Run Code Online (Sandbox Code Playgroud)