猿问

在张量流中是否有与 list.append() 类似的功能?

最近遇到一个问题,就是把每张图片的二进制码(tf.string类型)一一预处理在一个有shape的占位符中


[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用imgs_combined = tf.zeros([1, 224, 224, 3], dtype=tf.float32) 初始化,在这种情况下我可以使用 tf.concat 来做这个操作,在最终结果中我删除了第一个元素。


但在通常的思维中,这个函数就像一个list.append()操作。


X = []

for i, datum in enumerate(data):

    x.append(datum)

请注意,这里我只用空列表初始化 X。


我想知道张量流中是否有与 list.append() 类似的功能?


或者.. 这段代码有没有更好的实现?初始化imgs_combined感觉很奇怪。


侃侃无极
浏览 354回答 1
1回答
随时随地看视频慕课网APP

相关分类

Python
我要回答