1
votes

I'm using Keras with Tensorflow backend. I want to create a custom loss function, which would get the Euclidean distance between the two histograms, but I get this error:

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

Therefore, I dont know how to define my loss function.

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))

I try to modify codes, but I get another error."h_true = tf.cast(h_true, dtype=tf.dtypes.float32) AttributeError: module 'tensorflow._api.v1.dtypes' has no attribute '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))

Last, this problem is solved by the Jakub. The solution is:

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))
1
Can you try casting y_true and y_pred both to float32? - jakub
Yes. I try to use this code, but I get another error."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)) - jack jack
You should update your question with what you tried. - jakub
And instead of dtype=tf.dtypes.float32, you can try dtype="float32". Note that it's a string. - jakub
Perfect! Problem solved. Thank you so much for your help! - jack jack

1 Answers

1
votes

The error

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

indicates that the tensors need to be cast to a common datatype. Float32 is probably a good data type to use in this case. Values can be cast with

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