【发布时间】:2019-11-15 20:13:32
【问题描述】:
我尝试建立自己的损失函数如下
import numpy as np
from keras import backend as K
def MyLoss(self, x_input, x_reconstruct):
a = np.copy(x_reconstruct)
a = np.asarray(a, dtype='float16')
a = np.floor(4*a)/4
return K.mean(K.square(a - x_input), axis=-1)`
在编译中,它说 ValueError:使用序列设置数组元素
x_input 和 x_reconstruct 都是 [m, n, 1] np 数组。最后一行代码其实是直接从 Keras 内置的 MSE 损失函数中复制过来的。
另外,我认为损失是按样本计算的。如果输入和重构输入的维度都是 [m, n, 1],那么 Keras 内置损失的结果也将是一个大小为 [m, n] 的矩阵。那么为什么它可以正常工作呢?
然后我尝试直接通过我们np的功能
def MyLoss(self, x_input, x_reconstruct):
a = np.copy(x_reconstruct)
a = np.asarray(a, dtype=self.precision)
a = np.floor(4*a)/4
Diff = a - x_input
xx = np.mean(np.square(Diff), axis=-1)
yy = np.sum(xx)
return yy
但错误仍然存在。我犯了什么错误?代码应该怎么写?
借用Make a Custom loss function in Keras in detail的建议,我尝试关注
def MyLoss(self, x_input, x_reconstruct):
if self.precision == 'float16':
K.set_floatx('float16')
K.set_epsilon(1e-4)
a = K.cast_to_floatx(x_input)
a = K.round(a*4.-0.5)/4.0
return K.sum(K.mean(K.square(x_input-a), axis=-1))
但同样的错误发生
【问题讨论】:
-
两个帮助调试的建议: 1) 在 return 语句之前插入一行,
print("got here"),这样您就可以验证问题出在最后一行的计算上; 2)输出x_input.shape和a.shape看是否兼容。 -
恐怕不行。当我调用
model.compile(loss=self.MyLoss, optimizer= CurOptimizer, metrics=CurMetrics)时,甚至在代码到达那里之前就发生了错误
标签: keras loss-function