【问题标题】:tf.keras custom metric is giving incorrect resultstf.keras 自定义指标给出不正确的结果
【发布时间】:2020-05-18 17:12:13
【问题描述】:

我在 tf.keras 中为多标签分类问题实现了一个自定义指标。

def multilabel_TP(y_true, y_pred, thres = 0.4):
  return (      
                  tf.math.count_nonzero(
                                         tf.math.logical_and(tf.cast(y_true, tf.bool),
                                         tf.cast(y_pred >= thres, tf.bool))
                                       )
         )

count_zero 函数产生整数结果,但在运行模型时它给了我浮点值。在 keras 模型范围之外尝试时,自定义函数会给出正确的结果。

 8/33 [======>.......................] - ETA: 27s - loss: 0.4294 - multilabel_TP: **121.6250** 
model.compile(loss = 'binary_crossentropy', metrics = multilabel_TP, optimizer= 'adam')
model.fit(train_sentences, y_train, batch_size= 128, epochs = 20, validation_data= (test_sentences, y_test))

为什么会这样?

【问题讨论】:

标签: python keras tensorflow2.0 tf.keras


【解决方案1】:

keras 进度条中显示的是您的损失/指标在批次上的运行平均值,因为模型是在批次上进行训练的,并且每批次之后权重都会发生变化。这就是您获得浮点值的原因。

您的指标还应该返回一个浮点值,可能是对批处理中的元素数量进行除法。那么度量值会更有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-27
    • 2017-12-14
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多