在TensorFlow中是否有类似于list.append()的功能?

4

最近我遇到了一个问题,需要对一个形状为placeholder的每个图像二进制代码(tf.string类型)进行预处理。

[batch_size] = [None]

然后我需要在预处理后连接每个结果。

显然,我无法创建一个FOR语句来解决这个问题。

因此,我使用了tf.while_loop来完成这个任务。代码如下:

in_ph = tf.placeholder(shape=[None], dtype=tf.string)
i = tf.constant(0)
imgs_combined = tf.zeros([1, 224, 224, 3], dtype=tf.float32)

def body(i, in_ph, imgs_combined):
    img_content = tf.image.decode_jpeg(in_ph[i], channels=3)
    c_image = some_preprocess_fn(img_content)
    c_image = tf.expand_dims(c_image, axis=0)
    # c_image shape [1, 224, 224, 3]
    return [tf.add(i, 1), in_ph, tf.concat([imgs_combined, c_image], axis=0)]

def condition(i, in_ph, imgs_combined):
    return tf.less(i, tf.shape(in_ph)[0])

_, _, image_4d = tf.while_loop(condition,
          body,
          [i, in_ph, imgs_combined],
          shape_invariants=[i.get_shape(), in_ph.get_shape(), tf.TensorShape([None, 224, 224, 3])])

image_4d = image_4d[1:, ...]

这段代码没有任何问题。但是,在这里,我使用imgs_combined来逐个连接每个图像。在这种情况下,imgs_combined = tf.zeros([1, 224, 224, 3], dtype=tf.float32)被用来初始化imgs_combined,这样我就可以使用tf.concat完成此操作,并在最终结果中删除了第一个元素。
但从正常思考的角度来看,这个函数就像是一个list.append()操作。
X = []
for i, datum in enumerate(data):
    x.append(datum)

请注意,我这里只是用空列表初始化X。
我想知道在tensorflow中是否有类似于list.append()的函数?
或者,有没有更好的实现方法来替代这段代码? 对于初始化imgs_combined,我感到很奇怪。

tf.concat可能有所帮助,但它与list.append不相似。 - Mitiku
1个回答

2
你可以尝试使用 tf.TensorArray()链接),它支持动态长度,并且可以将值写入或读取到指定的索引位置。
import tensorflow as tf

def condition(i, imgs_combined):
    return tf.less(i, 5)
def body(i, imgs_combined):
    c_image = tf.zeros(shape=(224, 224, 3),dtype=tf.float32)
    imgs_combined = imgs_combined.write(i, c_image)
    return [tf.add(i, 1), imgs_combined]

i = tf.constant(0)
imgs_combined = tf.TensorArray(dtype=tf.float32,size=1,dynamic_size=True,clear_after_read=False)

_, image_4d = tf.while_loop(condition,body,[i, imgs_combined])
image_4d = image_4d.stack()

with tf.Session() as sess:
    image_4d_value = sess.run(image_4d)
    print(image_4d_value.shape)

#print
(5, 224, 224, 3)

@JavaFresher 不客气。如果回答有帮助并且没有问题,请接受答案。 - giser_yugang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接