gpt4 book ai didi

python - 如何在theano上实现加权二进制交叉熵?

转载 作者:太空狗 更新时间:2023-10-29 21:09:32 24 4
gpt4 key购买 nike

如何在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)

但我在下面收到此错误:

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


引用:https://github.com/fchollet/keras/issues/2115

引用:https://groups.google.com/forum/#!topic/theano-users/R_Q4uG9BXp8

最佳答案

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

关于python - 如何在theano上实现加权二进制交叉熵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39412051/

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