【发布时间】:2021-08-02 05:01:28
【问题描述】:
我正在使用带有 Tensorflow 后端的 Keras。我想创建一个自定义损失函数,它会得到两个直方图之间的欧几里得距离,但我得到了这个错误:
TypeError: 'Mul' Op 的输入 'y' 的 float32 类型与参数 'x' 的 int32 类型不匹配。
因此,我不知道如何定义我的损失函数。
def myloss(y_true, y_pred):
h_true = tf.histogram_fixed_width( y_true, value_range=(0,1), nbins=20)
h_pred = tf.histogram_fixed_width( y_pred, value_range=(0,1), nbins=20)
return K.mean(K.square(h_true - h_pred))
我尝试修改代码,但出现另一个错误。"h_true = tf.cast(h_true, dtype=tf.dtypes.float32) AttributeError: 模块 'tensorflow._api.v1.dtypes' 没有属性 'float32'"
def myloss(y_true, y_pred):
h_true = tf.histogram_fixed_width( y_true, value_range=(0,1), nbins=20)
h_pred = tf.histogram_fixed_width( y_pred, value_range=(0,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))
最后,Jakub 解决了这个问题。解决办法是:
def myloss(y_true, y_pred):
h_true = tf.histogram_fixed_width( y_true, value_range=(0,1), nbins=20)
h_pred = tf.histogram_fixed_width( y_pred, value_range=(0,1), nbins=20)
h_true = tf.cast(h_true, dtype="float32")
h_pred = tf.cast(h_pred, dtype="float32")
return K.mean(K.square(h_true - h_pred))
【问题讨论】:
-
您可以尝试将
y_true和y_pred都转换为float32 吗? -
是的。我尝试使用此代码,但出现另一个错误。"h_true = tf.cast(h_true, dtype=tf.dtypes.float32) AttributeError: module 'tensorflow._api.v1.dtypes' has no attribute 'float32'" h_true = tf.histogram_fixed_width( y_true, value_range=(0,1), nbins=20) h_pred = tf.histogram_fixed_width( y_pred, value_range=(0,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))
-
您应该用您尝试过的内容更新您的问题。
-
你可以试试
dtype=tf.dtypes.float32,而不是dtype=tf.dtypes.float32。请注意,它是一个字符串。 -
完美!问题解决了。非常感谢您的帮助!
标签: python tensorflow machine-learning keras loss-function