用于图像分割的keras中自定义损失函数的nan损失

时间:2019-10-21 06:30:03

标签: python tensorflow keras deep-learning caffe

我正在尝试为图像分割网络在keras中实现自定义损失功能。但是,当我训练模型时,我的损失是nan。这是自定义损失函数:

def seedloss(y_true,y_pred):
    count = K.sum(K.abs(y_true),axis=[1,2,3],keepdims = True)
    loss = -K.mean(K.sum(y_true*K.log(K.abs(y_pred)),axis=[1,2,3],keepdims=True)/(count))
    return loss

这是我将Caffe中以下给定的损失函数转换为喀拉斯语:

class SeedLossLayer(caffe.Layer):

def setup(self, bottom, top):
    if len(bottom) != 2:
        raise Exception("The layer needs two inputs!")

    probs = T.ftensor4()
    labels = T.ftensor4()

    count = T.sum(labels, axis=(1, 2, 3), keepdims=True)
    loss_balanced = -T.mean(T.sum(labels * T.log(probs), axis=(1, 2, 3), keepdims=True) / count)

    self.forward_theano = theano.function([probs, labels], loss_balanced)
    self.backward_theano = theano.function([probs, labels], T.grad(loss_balanced, probs))

def reshape(self, bottom, top):
    top[0].reshape(1)

def forward(self, bottom, top):
    top[0].data[...] = self.forward_theano(bottom[0].data[...], bottom[1].data[...])

def backward(self, top, prop_down, bottom):
    grad = self.backward_theano(bottom[0].data[...], bottom[1].data[...])
    bottom[0].diff[...] = grad

我的实现是否存在任何问题。为什么我会nan蒙受损失。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您的损失函数看起来是否可微?您可能需要为其添加平滑常数。