【问题标题】:Keras custom loss: histogramsKeras 自定义损失:直方图
【发布时间】: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_truey_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


【解决方案1】:

错误

TypeError: Input 'y' of 'Mul' Op has type float32 that does not match 
  type int32 of argument 'x'.

表示需要将张量转换为通用数据类型。在这种情况下,Float32 可能是一种很好的数据类型。值可以使用

x = tf.cast(x, "float32")

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2017-12-18
    • 2020-03-27
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多