tf.strings.format自动将标量张量作为列表



tf.strings.format功能自动包装单独张量作为列表。

例如,如果我想做这样的事情:

x = tf.convert_to_tensor('x')
[tf.strings.format("/path/to/directory/{}_{}.png", (x, y)) for y in range(2)]

输出将是:

[<tf.Tensor: id=712, shape=(), dtype=string, numpy=b'/path/to/directory/[x]_0.png'>,
 <tf.Tensor: id=714, shape=(), dtype=string, numpy=b'/path/to/directory/[x]_1.png'>]

所需的输出是:

[<tf.Tensor: id=712, shape=(), dtype=string, numpy=b'/path/to/directory/x_0.png'>,
 <tf.Tensor: id=714, shape=(), dtype=string, numpy=b'/path/to/directory/x_1.png'>]

编辑:

您可以通常与+运算符相连:

import tensorflow as tf
with tf.Graph().as_default(), tf.Session() as sess:
    x = tf.convert_to_tensor('x')
    path = tf.constant("/path/to/directory/")
    sep = tf.constant("_")
    ext = tf.constant(".png")
    res = [path + x + sep + tf.constant(str(y)) + ext for y in range(2)]
    print(sess.run(res))
    # [b'/path/to/directory/x_0.png', b'/path/to/directory/x_1.png']

或者,如果您不介意重新创建恒定张量(您可能不在急切的模式下(,则仅:

res = ["/path/to/directory/" + x + "_" + str(y) + ".png" for y in range(2)]

您可以使用tf.strings.join获得所需的结果:

import tensorflow as tf
with tf.Graph().as_default(), tf.Session() as sess:
    a = tf.convert_to_tensor('a')
    b = tf.convert_to_tensor('b')
    c = tf.convert_to_tensor('c')
    print(sess.run(tf.strings.join([a, b, c], '/')))
    # b'a/b/c'

最新更新