将字符串张量转换为字符串列表

时间:2020-04-12 16:05:33

标签: python tensorflow

有人如何转换以下字符串tensorflow张量:

<tf.Tensor: shape=(64,), dtype=string, numpy=
array([b'example string 1',
       b'example string 2',
       b'example string 3',

       ...

       b'example string 63',
       b'example string 64'],
      dtype=object)>

到字符串列表:

[
    'example string 1',
    'example string 2',
    'example string 3',

       ...

    'example string 63',
    'example string 64'
]

应用矢量化方法?

谢谢。

2 个答案:

答案 0 :(得分:1)

只需使用list(tensor.numpy())。示例:

import tensorflow as tf

n_strings = 8
t = tf.convert_to_tensor(['example string ' + str(i) for i in range(n_strings)])
t
# <tf.Tensor: shape=(8,), dtype=string, numpy=
# array([b'example string 0', b'example string 1', b'example string 2',
#        b'example string 3', b'example string 4', b'example string 5',
#        b'example string 6', b'example string 7'], dtype=object)>
list(t.numpy().astype('str'))
# ['example string 0',
#  'example string 1',
#  'example string 2',
#  'example string 3',
#  'example string 4',
#  'example string 5',
#  'example string 6',
#  'example string 7']

答案 1 :(得分:0)

作为替代方案,list(t.numpy().decode('utf-8')) 对我有用。