问题描述
确实是一个简单的问题,但似乎无法在 TensorFlow 文档中或通过谷歌搜索找到函数.
Simple question really but cannot seem to find a function in the TensorFlow docs or by googling.
如何将 tf.int32
类型的张量转换为 tf.string
类型的张量?
How can I convert a tensor of type tf.int32
to one of type tf.string
?
我试着用这样的东西简单地投射它:
I tried simply casting it with something like this:
x = tf.constant([1,2,3], dtype=tf.int32)
x_as_string = tf.cast(x, dtype=tf.string) # hoping for this output: [ '1', '2', '3' ]
with tf.Session() as sess:
res = sess.run(x_as_string)
但点击错误信息:
不支持将 int32 转换为字符串
文档中是否有我遗漏的简单函数?
Is there a simple function somewhere in the documentation that I am missing?
更新:
澄清:我意识到我可以使用带有 tf.py_func
的 python 函数解决"这个问题,但询问 TensorFlow 本身是否有解决方案
To clarify: I realise I could 'work around' this issue using a python function with tf.py_func
but asking if there is a solution in TensorFlow itself
推荐答案
您可以使用新添加的 (v1.12.0) tf.strings.format
:
You can do that with the newly added (v1.12.0) tf.strings.format
:
import tensorflow as tf
x = tf.constant([1, 2, 3], dtype=tf.int32)
x_as_string = tf.map_fn(lambda xi: tf.strings.format('{}', xi), x, dtype=tf.string)
with tf.Session() as sess:
res = sess.run(x_as_string)
print(res)
# [b'1' b'2' b'3']
对于 Tensorflow v2,
For Tensorflow v2,
import tensorflow as tf
x = tf.constant([1, 2, 3], dtype=tf.int32)
x_as_string = tf.map_fn(lambda xi: tf.strings.format('{}', xi), x, dtype=tf.string)
print(x_as_string.numpy())
# [b'1' b'2' b'3']
这篇关于Tensorflow - 如何将 int32 转换为字符串(使用 Python API for Tensorflow)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!