如何在Theano上实现加权二元交叉熵?

8
如何在Theano上实现加权二元交叉熵?我的卷积神经网络只能预测0~1(sigmoid)。我想以这种方式惩罚我的预测:

Cost-Table

基本上,我希望在模型预测为0但实际为1时进行更多的惩罚。
问题:如何使用Theano和Lasagne创建加权二元交叉熵函数?
我尝试了下面这个:
prediction = lasagne.layers.get_output(model)


import theano.tensor as T
def weighted_crossentropy(predictions, targets):

    # Copy the tensor
    tgt = targets.copy("tgt")

    # Make it a vector
    # tgt = tgt.flatten()
    # tgt = tgt.reshape(3000)
    # tgt = tgt.dimshuffle(1,0)

    newshape = (T.shape(tgt)[0])
    tgt = T.reshape(tgt, newshape)

   #Process it so [index] < 0.5 = 0 , and [index] >= 0.5 = 1


    # Make it an integer.
    tgt = T.cast(tgt, 'int32')


    weights_per_label = theano.shared(lasagne.utils.floatX([0.2, 0.4]))

    weights = weights_per_label[tgt]  # returns a targets-shaped weight matrix
    loss = lasagne.objectives.aggregate(T.nnet.binary_crossentropy(predictions, tgt), weights=weights)

    return loss

loss_or_grads = weighted_crossentropy(prediction, self.target_var)

但是我收到了以下错误信息:
类型错误:在重新整形时,新形状必须是向量或标量的列表/元组。在转换为向量后,得到Subtensor{int64}.0。

参考资料:https://github.com/fchollet/keras/issues/2115

参考资料:https://groups.google.com/forum/#!topic/theano-users/R_Q4uG9BXp8


2
由于您正在使用 binary_crossentropy(..),每次错误的预测都会受到惩罚。实际上,您需要考虑如何处理不平衡的数据集,这个链接可能会有所帮助。 - uyaseen
哪一行出现了错误? - Jules G.M.
2个回答

2

感谢Lasagne团队的开发人员,通过构建自己的损失函数,我解决了这个问题。

loss_or_grads = -(customized_rate * target_var * tensor.log(prediction) + (1.0 - target_var) * tensor.log(1.0 - prediction))

loss_or_grads = loss_or_grads.mean()

0

针对您的语法错误:

请更改

newshape = (T.shape(tgt)[0])
tgt = T.reshape(tgt, newshape)

newshape = (T.shape(tgt)[0],)
tgt = T.reshape(tgt, newshape)

T.reshape 需要一个轴的元组,你没有提供,因此出错。

在惩罚假阴性(预测为 0、真实值为 1)之前,请确保这种预测错误不是基于您的训练数据统计信息,就像 @uyaseen 建议的那样。


但是我如何对更确定的目标/预测进行惩罚?就像我发布的表格/图片上所示的那样? - KenobiBastila
您可以使用类权重来增加您最关心的类别的损失。这主要用于平衡训练数据,但通常只是一种增加特定类别错误的方法。 - nemo
但是我该如何在Lasagne上实现呢? - KenobiBastila

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接