如何将tf.int64转换为tf.float32?

Yee*_*Liu 24 int64 tensorflow

我试过了:

test_image = tf.convert_to_tensor(img, dtype=tf.float32)
Run Code Online (Sandbox Code Playgroud)

然后出现以下错误:

ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int64: 'Tensor("test/ArgMax:0", shape=TensorShape([Dimension(None)]), dtype=int64)'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ald 37

你可以使用以下方式施放:

tf.cast(my_tensor, tf.float32)
Run Code Online (Sandbox Code Playgroud)

将tf.float32替换为您想要的类型.


编辑:至少目前看来,这tf.cast不会转换为无符号的dtype(例如tf.uint8).要解决此问题,您可以转换为已签名的等效项并用于tf.bitcast获取所有权限.例如

tf.bitcast(tf.cast(my_tensor, tf.int8), tf.uint8)
Run Code Online (Sandbox Code Playgroud)


Yee*_*Liu 12

哎呀,我在API中找到了这个函数......

 tf.to_float(x, name='ToFloat')
Run Code Online (Sandbox Code Playgroud)

  • `tf.to_float()` 现已弃用,应使用 `tf.cast()` 代替。 (2认同)

sta*_*010 5

您可以使用其中任何一个tf.cast(x, tf.float32)tf.to_float(x)两个,转换为float32.

例:

sess = tf.Session()

# Create an integer tensor.
tensor = tf.convert_to_tensor(np.array([0, 1, 2, 3, 4]), dtype=tf.int64)
sess.run(tensor)
# array([0, 1, 2, 3, 4])

# Use tf.cast()
tensor_float = tf.cast(tensor, tf.float32)
sess.run(tensor_float)
# array([ 0.,  1.,  2.,  3.,  4.], dtype=float32)

# Use tf.to_float() to cast to float32
tensor_float = tf.to_float(tensor)
sess.run(tensor_float)
# array([ 0.,  1.,  2.,  3.,  4.], dtype=float32)
Run Code Online (Sandbox Code Playgroud)