2d 张量列表到一个 3d 张量

List of 2d Tensors to one 3d Tensor

我有一个单词嵌入的句子列表。所以每一句话都是一个16*300的矩阵,所以是一个2d张量。我想将它们连接到 3d 张量并将此 3d 张量用作 CNN 模型的输入。不幸的是,我无法将它放入这个 3d 张量中。

在我看来,至少通过 tf.concat 将这些 2d 张量中的两个连接到一个较小的 3d 张量应该可行。不幸的是,我收到以下错误消息

tf.concat(0, [Tweets_final.Text_M[0], Tweets_final.Text_M[1]])

ValueError: Shape (3, 16, 300) must have rank 0

如果它适用于两个二维张量,我可能会使用一个循环

列表中的这些二维张量之一如下所示:

<tf.Tensor: shape=(16, 300), dtype=float32, numpy= array([[-0.03571776,  0.07699937, -0.02208528, ...,  0.00873246,
    -0.05967658, -0.03735098],
   [-0.03044251,  0.050944  , -0.02236165, ..., -0.01745957,
     0.01311598,  0.01744673],
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ],
   ...,
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ]], dtype=float32)>

您可以在文档中找到解决方案: https://www.tensorflow.org/api_docs/python/tf/stack

tf.stack:将 rank-R 个张量的列表堆叠成一个等级 - (R+1) 张量。

>>> x = tf.constant([1, 4])
>>> y = tf.constant([2, 5])
>>> z = tf.constant([3, 6])
>>> tf.stack([x, y, z])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 4],
       [2, 5],
       [3, 6]], dtype=int32)>
>>> tf.stack([x, y, z], axis=1)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)>