gpt4 book ai didi

python - keras 中的自定义二进制交叉熵损失忽略没有非零值的列

转载 作者:太空宇宙 更新时间:2023-11-03 20:22:56 25 4
gpt4 key购买 nike

我正在尝试对标签非常稀疏的数据进行分段。因此,我只想计算至少具有一个非零值的列中的梯度。

我尝试了一些方法,其中我应用了额外的输入,即这些非零列的掩码,但考虑到所有必要的信息已包含在 y_true 中,该方法仅查看y_true 找到掩码肯定会更好。

如果我用 numpy 实现它,它可能看起来像这样:

def loss(y_true, y_pred):
indices = np.where(np.sum(y_true, axis=1) > 0)
return binary_crossentropy(y_true[indices], y_pred[indices])

y_truey_pred 在此示例中是矢量化 2D 图像。

如何将其“转换”为可微分的 Keras 损失函数?

最佳答案

通过 tfkeras.backend 使用 tf 兼容操作:

import tensorflow as tf
import keras.backend as K
from keras.losses import binary_crossentropy

def custom_loss(y_true, y_pred):
indices = K.squeeze(tf.where(K.sum(y_true, axis=1) > 0))
y_true_sparse = K.cast(K.gather(y_true, indices), dtype='float32')
y_pred_sparse = K.cast(K.gather(y_pred, indices), dtype='float32')
return binary_crossentropy(y_true_sparse, y_pred_sparse) # returns a tensor

我不确定你的问题的确切维度规范,但损失必须评估为单个值 - 上面没有,因为你正在传递多维预测和标签。为了减少暗淡,请将上面的返回包裹起来,例如K.mean。示例:

y_true = np.random.randint(0,2,(10,2))
y_pred = np.abs(np.random.randn(10,2))
y_pred /= np.max(y_pred) # scale between 0 and 1

print(K.get_value(custom_loss(y_true, y_pred))) # get_value evaluates returned tensor
print(K.get_value(K.mean(custom_loss(y_true, y_pred))
>> [1.1489482 1.2705883 0.76229745 5.101402 3.1309896] # sparse; 5 / 10 results
>> 2.28284 # single value, as required

(最后,请注意,这种稀疏性会通过从总标签/预测计数中排除全零列来使损失产生偏差;如果不需要,您可以通过 K.sumK 进行平均.shapeK.size)

关于python - keras 中的自定义二进制交叉熵损失忽略没有非零值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58040789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com