【问题标题】:Is there any similar funtion as list.append() in tensorflow?tensorflow中是否有与list.append()类似的功能?
【发布时间】:2018-12-29 09:31:25
【问题描述】:

最近遇到一个问题,将每张图片的二进制码(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 初始化为 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。

我想知道tensorflow中有没有类似list.append()的函数?

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

【问题讨论】:

  • tf.concat 可能会有所帮助。但它与 list.append 不同。

标签: python tensorflow


【解决方案1】:

你可以试试tf.TensorArray()(link),支持动态长度,可写可读
值到指定的索引。

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 不客气。如果有帮助且没问题,请采纳答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多