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



我正在尝试在 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 中以下给定的损失函数转换为 keras:

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。有人可以帮我吗?

看起来你的损失函数不是可微的?您可能希望向其添加平滑常量。

最新更新