Python Keras自定义损失:直方图

Python Keras自定义损失:直方图,python,tensorflow,machine-learning,keras,loss-function,Python,Tensorflow,Machine Learning,Keras,Loss Function,我在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_pre

我在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.\u api.v1.dtypes”没有属性“float32”

def myloss(y_true,y_pred):

最后,这个问题由Jakub解决。解决办法是:

def myloss(y_true,y_pred):

错误

TypeError: Input 'y' of 'Mul' Op has type float32 that does not match 
  type int32 of argument 'x'.
指示需要将张量转换为公共数据类型。在这种情况下,Float32可能是一种很好的数据类型。值可以使用

x=tf.cast(x,“float32”)

你能试着将
y\u true
y\u pred
都转换为float32吗?是的。我试图使用这段代码,但我得到了另一个错误。“h_true=tf.cast(h_true,dtype=tf.dtypes.float32)AttributeError:module'tensorflow.\u api.v1.dtypes'没有属性'float32'”h_true=tf.histogram\u fixed\u width(y_true,value\u range=(0,1),nbins=20)h_pred=tf.histogram\u fixed\u width\u width\u宽度(y\u pred,value\u 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)返回K.mean(K.square(h_true-h_pred))您应该用您尝试过的内容更新您的问题。您可以尝试
dtype=tf.dtypes.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="float32")

 h_pred = tf.cast(h_pred, dtype="float32")

 return K.mean(K.square(h_true - h_pred))
TypeError: Input 'y' of 'Mul' Op has type float32 that does not match 
  type int32 of argument 'x'.