【问题标题】:Tensorflow: Stringify tensor as a whole (without creating tensor of strings)Tensorflow:将张量作为一个整体进行字符串化(不创建字符串张量)
【发布时间】:2020-03-03 10:58:46
【问题描述】:

我有以下数组,

a = tf.random.uniform((5,2), 0, 10)

<tf.Tensor: shape=(5, 2), dtype=float32, numpy=
array([[3.8656425 , 6.7514324 ],
       [0.49138665, 3.5968459 ],
       [4.435692  , 4.7223845 ],
       [7.3588967 , 0.31867146],
       [1.6837907 , 3.2266355 ]], dtype=float32)>

我想要的是像下面这样的字符串化数组数组,这将返回一个 numpy 数组,但我想做 tensorflow ops 以返回一个张量:

list(map(str, a.numpy()))

['[3.8656425 6.7514324]',
 '[0.49138665 3.5968459 ]',
 '[4.435692  4.7223845]',
 '[7.3588967  0.31867146]',
 '[1.6837907 3.2266355]']

当我使用tf.as_string()

tf.as_string(a)

<tf.Tensor: shape=(5, 2), dtype=string, numpy=
array([[b'3.865643', b'6.751432'],
       [b'0.491387', b'3.596846'],
       [b'4.435692', b'4.722384'],
       [b'7.358897', b'0.318671'],
       [b'1.683791', b'3.226635']], dtype=object)>

我也尝试过使用

tf.map_fn(tf.as_string, a, dtype=tf.string)

# Same output as above

tf.as_string() 将 float/int 张量转换为相同形状的字符串张量。 是否有任何 tensorflow 操作可以将张量作为一个整体进行字符串化?

【问题讨论】:

  • 您使用的是什么版本的 TensorFlow?您是否需要将结果作为张量并仅使用 TensorFlow 操作,还是可以获取 NumPy 数组然后将其转换为字符串?
  • 我正在使用 tensorflow 2;我需要一个张量结果,我不想使用问题中提到的 numpy 方式(或类似方法),然后将其转换为张量。我想要一个返回张量的操作,谢谢

标签: python arrays string tensorflow


【解决方案1】:

你可以使用tf.strings.format:

import tensorflow as tf

tf.random.set_seed(0)
a = tf.random.uniform((5,2), 0, 10)
b = tf.map_fn(lambda r: tf.strings.format('{}', r, summarize=-1), a, tf.string)
print(b)
# tf.Tensor(
# [b'[2.91975141 2.06566453]' b'[5.35390759 5.61257458]'
#  b'[4.16674519 8.0782795]' b'[4.93225098 9.98129272]'
#  b'[6.96735144 1.25373602]'], shape=(5,), dtype=string)

【讨论】:

    【解决方案2】:

    作为一种解决方法,我将加入单个字符串

    b = tf.map_fn(lambda x: tf.strings.join(x, separator=" "), tf.as_string(a))
    b = tf.map_fn(lambda x: tf.strings.join(['[', x, ']']), b)
    
    <tf.Tensor: shape=(5,), dtype=string, numpy=
    array([b'[3.865643 6.751432]', b'[0.491387 3.596846]',
           b'[4.435692 4.722384]', b'[7.358897 0.318671]',
           b'[1.683791 3.226635]'], dtype=object)>
    
    

    欢迎其他答案:)

    【讨论】:

    • 这不是解决方法,这是解决方法。您的误解是您认为tf.Tensor 中矩阵的每一行都是一个张量,或者它属于一起或其他什么。你可能会这么想,但tensorflow 不会。您可以在&lt;tf.Tensor: shape=(5, 2), ... 中看到,它只是一个 5x2 矩阵。它可能是printed 作为列表列表,但不是,它是tf.Tensor。所以,你需要一些额外的步骤来获得你想要的东西。由于您对额外步骤的整个实施都在tensorflow,这个LGTM。
    • 我的目标是简单地将张量作为一个整体进行字符串化,在我在问题中给出的示例中,我试图做同样的事情,除了每个元素在张量中(即在 map_fn 内)。我期待一个内置的 tf fn 可以做到这一点。也就是说,我同意 tensorflow 可能会做一些类似于使用tf.strings.format 进行格式化的事情,不过有更多花哨的选项。
    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2018-10-12
    • 2023-03-04
    • 2018-08-04
    相关资源
    最近更新 更多