【问题标题】:How to feed a TensorArray to a TensorFlow session如何将 TensorArray 提供给 TensorFlow 会话
【发布时间】:2017-07-06 11:08:17
【问题描述】:

我的 TensorFlow 图的输入之一是可变长度数组的列表(例如 [[0, 1, 2], [3, 4], [5, 6, 7, 8])。为了表示这一点,我在图中使用了 TensorArray。

但是,在运行图表时,我找不到输入一批 TensorArrays 的方法,因为 feed_dict={ some_ta: [[0, 1, 2], [3, 4], [5, 6, 7, 8]] } 不起作用。

目前是否有任何解决方法可以让我直接将 TensorArrays 输入到会话中?

【问题讨论】:

    标签: python numpy machine-learning tensorflow


    【解决方案1】:

    对于这种情况没有开箱即用的解决方案,但您可以尝试解决方法。

    1. 最简单的解决方法是填充所有输入数据(例如用零填充),以使所有数组具有相同的维度。请注意,张量流旨在使用 张量 执行计算,张量具有矩形而非可变形状。因此,这样您的操作可能会更快完成,但您需要调整算法以忽略尾随零。

      在上面的例子中,代码很简单:

      # can hold any number of 4-D vectors
      input = tf.placeholder(dtype=tf.float32, shape=[None, 4])
      with tf.Session() as session:
        data = [[0, 1, 2, 0], [3, 4, 0, 0], [5, 6, 7, 8]]
        print session.run(input, feed_dict={input: data})
      
    2. 如果长度恰好是固定的,您可以这样对输入进行分区

      input = tf.placeholder(dtype=tf.float32, shape=[None])
      split = tf.dynamic_partition(input, partitions=[0, 0, 0, 1, 1, 2, 2, 2, 2], num_partitions=3)
      
      with tf.Session() as session:
        data = [0, 1, 2, 3, 4, 5, 6, 7, 8]
        print session.run(split, feed_dict={input: data})
      

      结果如下:

      [array([ 0.,  1.,  2.], dtype=float32), array([ 3.,  4.], dtype=float32), array([ 5.,  6.,  7.,  8.], dtype=float32)]
      

      partitions参数不能是张量,所以在建图的时候必须静态知道。

    3. 要执行真正的任意拆分,您将自己手动执行此操作。您仍然将 data 作为单个数组传递,同时 partitions 保存分区索引。然后您可以按照this questionthis question 中的建议执行繁琐的拆分。我不建议你走这条路,除非绝对没有其他办法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 2018-09-15
      相关资源
      最近更新 更多