首页 文章

向批量的TensorFlow张量添加行

提问于
浏览
1

我有3个张量[batch_size,num_rows,num_cols]),我想要追加适当大小的行,从而得到维度为3的张量[batch_size,num_rows 1,num_cols]

例如,如果我有以下批次的2x2矩阵

batch = [ [[2, 2],
           [2, 2]],
          [[3, 3],
           [3, 3]],
          [[4, 4],
           [4, 4]] ]

和一个新行 v = [1, 1] 我想追加,然后想要的结果是

new_batch = [ [[2, 2],
               [2, 2],
               [1, 1]], 
              [[3, 3],
               [3, 3],
               [1, 1]],
              [[4, 4],
               [4, 4],
               [1, 1]] ]

在TensorFlow中有一种简单的方法吗?这是我尝试过的:

W, b, c0, q0 = params
c = tf.concat([context, c0], axis=1)
q_p = tf.tanh(tf.matmul(W, question) + b)
q = tf.concat([q_p, q0], axis=1)
q_mask = tf.concat([question_mask, 1], axis=1)

澄清条款,

  • context 的尺寸为 [batch_size, context_len, hidden_size]

  • q_p 的尺寸为 [batch_size, question_len, hidden_size]

  • question_mask 的尺寸为 [batch_size, question_len]

  • c0q0 都有尺寸 [hidden_size]

我想做的事

  • 将矢量 c0 添加到 context ,从而产生尺寸为 [batch_size, context_len + 1, hidden_size] 的Tensor

  • 将矢量 q0 添加到 q_p ,产生尺寸为 [batch_size, question_len + 1, hidden_size] 的Tensor

  • 将1添加到 question_mask ,产生尺寸为 [batch_size, question_len + 1] 的Tensor

谢谢您的帮助 .

1 回答

  • 1

    您可以使用tf.map_fn执行此操作 .

    batch = [ [[2, 2],
               [2, 2]],
              [[3, 3],
               [3, 3]],
              [[4, 4],
               [4, 4]] ]
    
    row_to_add = [1,1]
    
    t = tf.convert_to_tensor(batch, dtype=np.float32)
    appended_t = tf.map_fn(lambda x: tf.concat((x, [row_to_add]), axis=0), t)
    

    输出

    appended_t.eval(session=tf.Session())
    
    array([[[ 2.,  2.],
            [ 2.,  2.],
            [ 1.,  1.]],
    
           [[ 3.,  3.],
            [ 3.,  3.],
            [ 1.,  1.]],
    
           [[ 4.,  4.],
            [ 4.,  4.],
            [ 1.,  1.]]], dtype=float32)
    

相关问题