如何将 TensorArray 提供给 TensorFlow 会话


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

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

目前是否有任何解决方法允许我直接将张量数组输入会话?

对于这种情况,没有现成的解决方案,但您可以尝试解决方法。

  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保存分区索引。然后,您可以按照此问题或此问题中的建议执行繁琐的拆分。我不建议你走这条路,除非绝对没有其他办法。

最新更新