如何在Theano上实现加权二元交叉熵?我的卷积神经网络只能预测0~1(sigmoid)。我想以这种方式惩罚我的预测:
基本上,我希望在模型预测为0但实际为1时进行更多的惩罚。
问题:如何使用Theano和Lasagne创建加权二元交叉熵函数?
我尝试了下面这个:
但是我收到了以下错误信息:
类型错误:在重新整形时,新形状必须是向量或标量的列表/元组。在转换为向量后,得到Subtensor{int64}.0。
问题:如何使用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
binary_crossentropy(..)
,每次错误的预测都会受到惩罚。实际上,您需要考虑如何处理不平衡的数据集,这个链接可能会有所帮助。 - uyaseen