Tensorflow中除数与被除数的数据类型必须一致

测试版本:Tensorflow r2.0

Tensorflow中除数与被除数的数据类型必须一致,否则会引发异常:TypeError: x and y must have the same dtype, got tf.float32 != tf.int32
可以通过tf.cast(value,tf.Dtype),进行类型转换解决。

a=tf.constant(10)
b=tf.constant(10)
a/b

Output:
<dtype: 'int32'> <dtype: 'int32'>
<tf.Tensor: shape=(), dtype=float64, numpy=1.0>
a=tf.cast(a,tf.float32)
print(a.dtype,b.dtype)
a/b

Output:
<dtype: 'float32'> <dtype: 'int32'>
...
TypeError: x and y must have the same dtype, got tf.float32 != tf.int32
b=tf.cast(b,tf.float32)
print(a.dtype,b.dtype)
a/b

Output:
<dtype: 'float32'> <dtype: 'float32'>
<tf.Tensor: shape=(), dtype=float32, numpy=1.0>

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×