【问题标题】:How to implement Weighted Binary CrossEntropy on theano?如何在 theano 上实现加权二元交叉熵?
【发布时间】:2017-01-17 15:11:08
【问题描述】:

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

我的卷积神经网络只预测 0 ~~ 1 (sigmoid)。

我想以这种方式惩罚我的预测:

基本上,当模型预测为 0 但事实为 1 时,我想惩罚更多。

问题:如何使用 theano 和 lasagne 创建这个 Weighted Binary CrossEntropy 函数?

我在下面试过这个

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)

但我在下面收到此错误:

TypeError:reshape 中的新形状必须是向量或标量列表/元组。转换为向量后得到 Subtensor{int64}.0。


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

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

【问题讨论】:

  • 由于您使用的是binary_crossentropy(..),因此每次错误预测都会受到惩罚。你真正需要的是看看如何处理不平衡的数据集,这个link 可能会有所帮助。
  • 错误来自哪一行

标签: python theano keras lasagne cross-entropy


【解决方案1】:

感谢千层面组的开发人员,我通过构建自己的损失函数解决了这个问题。

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()

【讨论】:

    【解决方案2】:

    解决您的语法错误:

    改变

    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 suggested

    【讨论】:

    • 但是我怎样才能惩罚更多的特定目标/预测呢?喜欢在我发布的桌子/图片上吗?
    • 你可以使用类权重来增加你最关心的类的损失。这主要用于平衡训练数据,但它通常只是增加一个特定类的错误的一种方法。
    • 是的,但我如何在千层面上实施?
    猜你喜欢
    • 2018-11-28
    • 1970-01-01
    • 2019-08-08
    • 2019-07-13
    • 2017-11-11
    • 2020-01-03
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多