我在Tensorflow后端使用Keras。我想创建一个新的自定义损失函数,在其中将y_true和y_pred的各个值合并到bin中(考虑直方图),然后计算两个直方图之间的chi2。
我了解张量对象是不可迭代的,因此无法遍历y_true和y_pred的各个元素来填充直方图。
我试图创建这样的损失函数:
def Chi2Loss(y_true, y_pred):
h_true = tf.histogram_fixed_width( y_true, value_range=(-1., 1.), nbins=20)
h_pred = tf.histogram_fixed_width( y_true, value_range=(-1., 1.), nbins=20)
return K.mean(K.square(h_true - h_pred))
但是我得到一个错误:
TypeError:“ Mul”操作的输入“ y”具有不匹配的float32类型 输入参数'x'的int32。
答案 0 :(得分:0)
我认为是因为y_pred
中没有直接使用Y_true
或return
,而喀拉拉邦抱怨。
您可以在喀拉拉邦使用这个小技巧:
def Chi2Loss(y_true, y_pred):
h_true = tf.histogram_fixed_width( y_true, value_range=(-1., 1.), nbins=20)
h_pred = tf.histogram_fixed_width( y_pred, value_range=(-1., 1.), nbins=20)
return K.mean(K.square(h_true - h_pred)) + y_pred*0
希望有帮助
答案 1 :(得分:0)
这是数字类型的问题:tf.histogram_fixed_width
只能提供int32
或int64
张量,而K.square
不支持任何这些格式。
解决方案:将tf.histogram_fixed_width
输出转换为兼容的数字类型,例如float32
:
def Chi2Loss(y_true, y_pred):
h_true = tf.histogram_fixed_width( y_true, value_range=(-1., 1.), nbins=20)
h_pred = tf.histogram_fixed_width( y_pred, value_range=(-1., 1.), nbins=20)
h_true = tf.cast(h_true, dtype=tf.dtypes.float32)
h_pred = tf.cast(h_pred, dtype=tf.dtypes.float32)
return K.mean(K.square(h_true - h_pred))