带有分数标签的 Keras 模型的 AUC 指标为零

问题描述

在这个简单的例子中,尽管预测是完美的(损失 0,准确度 1),但 AUC 为零:

import numpy as np
import tensorflow as tf

# enable debugging of tf.keras.metrics.AUC.update_state and .result
tf.config.run_functions_eagerly(True)

# simple model connecting a scalar input to a scalar output
layer = tf.keras.layers.Input(shape=1)
model = tf.keras.models.Model(inputs=layer,outputs=layer)

# prepare data: [0.1,0.2,... 0.9]
data = np.arange(1,10) / 10
print(f"data = {data}")

# compile and fit model using accuracy and AUC metrics
model.compile(metrics=["categorical_accuracy","AUC"])
history = model.fit(x=data,y=data,verbose=0)
print(f"metrics = {history.history}")

输出

data = [0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
metrics = {'loss': [0.0],'categorical_accuracy': [1.0],'auc': [0.0]}

原因有两个:

  1. keras.utils.metrics_utils.update_confusion_matrix_variables 将所有标签强制转换为 bool,因此所有标签都属于“true”类。

https://github.com/tensorflow/tensorflow/blob/834e7ddb83/tensorflow/python/keras/utils/metrics_utils.py#L380

  1. 由于 self.false_positives 全为零,因此与 x == fp_rate 成正比的结果也为零:

https://github.com/tensorflow/tensorflow/blob/834e7ddb83/tensorflow/python/keras/metrics.py#L2248-L2250

https://github.com/tensorflow/tensorflow/blob/834e7ddb83/tensorflow/python/keras/metrics.py#L2285-L2287

我不知道我该怎么办。文档说对于

实际 AUC 的最佳近似值,predictions 应在 [0,1] 范围内大致均匀分布

https://github.com/tensorflow/tensorflow/blob/834e7ddb83/tensorflow/python/keras/metrics.py#L1875-L1879

就是这样。我认为作者没有设想人们进行逐元素手动标签平滑(我这样做是为了实现逐样本标签平滑)。

问题可以简化为这样,也打印AUC = 0.0

import numpy as np
import tensorflow as tf

# prepare data: [0.1,10) / 10
print(f"data = {data}")

# compute AUC metric
m = tf.keras.metrics.AUC(num_thresholds=3)
m.update_state(data,data)
print(f"AUC = {m.result().numpy()}")

这是预期的吗?如果是这样,我可以使用某种分类 AUC 吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)