Tensorflow-如何将int32转换为字符串(使用用于Tensorflow的Python API)



这个问题很简单,但似乎无法在TensorFlow文档中或通过谷歌搜索找到函数。

如何将tf.int32类型的张量转换为tf.string类型的张量?

我试着简单地用这样的东西铸造它:

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强制转换为字符串

文档中是否缺少一个简单的函数?


更新:

澄清一下:我意识到我可以使用tf.py_func的python函数来"解决"这个问题,但询问TensorFlow本身是否有解决方案

tf.as_string((将给定张量中的每个条目转换为字符串。支持许多数字

您可以使用新添加的(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,

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']

最新更新