【问题标题】:TensorFlow: stacking tensors in while loopTensorFlow:在while循环中堆叠张量
【发布时间】:2018-06-05 22:18:57
【问题描述】:

我正在尝试实现一个循环,该循环遍历张量的行,检索每行中的索引,使用它们从另一个张量收集向量,最后将这些向量组合到一个新的张量中。 问题是每一行可能包含不同数量的索引(例如 [[-1,-1,1,4,-1], [3,-1,-1,-1,-1]] 第一行索引: [1, 4];第二行索引 [3])。 当我使用 tf.while_loop 或 tf.scan 时,问题就出现了。对于第一个,我不明白如何将所有收集的张量堆叠在一起。相反,第二个希望所有输出具有相同的形状(似乎我无法判断所有输出都具有 [None, 10] 的一般形状)。

有没有人尝试过类似的东西?

我附上了 while_loop 的代码:

i = tf.constant(0)
def body(i, merging):
    i += 1
    print('i', i)
    i_row = tf.gather(dense, [i])
    i_indices = tf.where(i_row > 0)[:, 1]
    i_vecs = tf.gather(embeddings_ph, i_indices)
    return i, i_vecs

tf.while_loop(lambda i, merging : tf.less(i, 2), body, 
              loop_vars=[i,merging], 
              shape_invariants=[i.get_shape(), 
                                tf.TensorShape((None, 3))],
              name='vecs_gathering')

这里缺少的是将所有 while_loop 输出(每个 i 的 i_vec)堆叠在一个新的张量中。

【问题讨论】:

    标签: python tensorflow while-loop stack deep-learning


    【解决方案1】:

    好的,从 rnn 实现中得到灵感。我修改了我的代码如下,现在它完美地工作了:

    def body(i, outputs):
        i_row = tf.gather(dense, [i])
        i_indices = tf.where(i_row > 0)[:, 1]
        i_vecs = tf.gather(embeddings_ph, i_indices)
        outputs = outputs.write(i, i_vecs)
        i += 1
    return i, outputs
    
    outputs = tf.TensorArray(dtype=tf.float32, infer_shape=False, size=1, 
                         dynamic_size=True) 
    _, outputs = tf.while_loop(lambda i, *_: tf.less(i, 3), body,[0,outputs])
    
    outputs = outputs.concat()
    

    我还想强调一个事实,即您必须在执行写入时重新分配 TensorArray 的值(否则 tf 会抱怨您没有使用您声明的数组这一事实)

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多