更改自定义度量中的yTrue

2024-04-25 23:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在Keras中实现GAN,我想使用One-sided label smoothing技巧,即把真图像的标签设为0.9,而不是1。然而,现在内置的度量binary_crossentropy并没有做正确的事情,对于真实图像,它总是0。你知道吗

然后我尝试在Keras中实现我自己的指标。我想把所有的0.9标签转换成1,但我对Keras还不熟悉,不知道怎么做。以下是我的意图:

# Just a pseudo code
def custom_metrics(y_true, y_pred):
    if K.equal(y_true, [[0.9]]):
        y_true = y_true+0.1
    return metrics.binary_accuracy(y_true, y_pred)

如何比较和更改y_true标签?提前谢谢!你知道吗


编辑: 以下代码的输出为:

def custom_metrics(y_true, y_pred):
    print(K.shape(y_true))
    print(K.shape(y_pred))
    y_true = K.switch(K.equal(y_true, 0.9), K.ones_like(y_true), K.zeros_like(y_true))
    return metrics.binary_accuracy(y_true, y_pred)

Tensor("Shape:0", shape=(2,), dtype=int32) Tensor("Shape_1:0", shape=(2,), dtype=int32)

ValueError:对于输入形状为[?,?], [?,?]. 你知道吗


Tags: 图像truereturndefcustom标签equallike
1条回答
网友
1楼 · 发布于 2024-04-25 23:26:35

您可以使用tf.where

y_true = tf.where(K.equal(y_true, 0.9), tf.ones_like(y_true), tf.zeros_like(y_true))

或者,您也可以使用keras.backend.switch函数。你知道吗

keras.backend.switch(condition, then_expression, else_expression)

您的自定义度量函数如下所示:

def custom_metrics(y_true, y_pred):
    y_true = K.switch(K.equal(y_true, 0.9),K.ones_like(y_true), K.zeros_like(y_true))
    return metrics.binary_accuracy(y_true, y_pred)

测试代码:

def test_function(y_true):
    print(K.eval(y_true))
    y_true = K.switch(K.equal(y_true, 0.9),K.ones_like(y_true), K.zeros_like(y_true))
    print(K.eval(y_true))

y_true = K.variable(np.array([0, 0, 0, 0, 0, 0.9, 0.9, 0.9, 0.9, 0.9]))
test_function(y_true)  

输出:

[0.  0.  0.  0.  0.  0.9 0.9 0.9 0.9 0.9]
[0. 0. 0. 0. 0. 1. 1. 1. 1. 1.]

相关问题 更多 >

    热门问题