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

时间:2019-07-08 10:32:09

标签: python tensorflow

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

1 个答案:

答案 0 :(得分:0)

编辑:

您可以使用+运算符正常连接字符串:

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'