2

我是神经网络和 keras 的新手,在编写这个自定义损失函数时遇到了麻烦:

损失函数

我使用 TensorFlow 作为后端。我看到了其他的例子,并以这种方式编写了损失函数:

from keras import backend as K
def depth_loss_func(pred_depth,actual_depth):
    n = pred_depth.shape[0]
    di = K.log(pred_depth)-K.log(actual_depth)
    di_sq = K.square(di)
    sum_d = K.sum(di)
    sum_d_sq = K.sum(di_sq)
    loss = ((1/n)*sum_d_sq)-((1/(n*n))*sum_d*sum_d) # getting an error in this step
    return loss

我得到的错误是: TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'

另外我不确定如何将学习率纳入损失函数。谢谢你的帮助。

4

2 回答 2

4

不要使用“n”,在我看来这似乎不是最优雅的方式,而是尝试使用以下K.mean函数:

di = K.log(pred_depth)-K.log(actual_depth)

di_mean = K.mean(di)
sq_mean = K.mean(K.square(di))

loss = (sq_mean - (lamb*di_mean*di_mean)) # getting an error in this step
于 2017-06-28T16:25:27.400 回答
2

张量的形状是未知的,直到您在图形执行期间向损失函数提供输入。为了在执行时动态计算形状,您可以使用K.shape().

将第一行更改为:

n = K.shape(pred_depth)[0]

关于学习率,只需将其作为另一个参数传递即可。如果它是动态的,您可以通过model.optimizer.lr.get_value().

于 2017-06-28T15:25:14.457 回答