首页 文章

TensorFlow:在while循环中堆叠张量

提问于
浏览
2

我正在尝试实现一个遍历张量行的循环,检索每一行中的索引,使用它们从另一个张量中收集向量,最后将这些向量组合在一个新的张量中 . 问题是每行可能包含不同数量的索引(例如[[-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)叠加在一起 .

1 回答

  • 2

    好的,从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会抱怨你没有使用你声明的数组)

相关问题