在 PyTorch 中连接不同大小的层

Concatenate layers with different sizes in PyTorch

在 Keras 中,可以连接两个不同大小的层:

# Keras — this works, conceptually
layer_1 = Embedding(50, 5)(inputs)
layer_2 = Embedding(300, 20)(inputs)
concat = Concatenate()([layer_1, layer_2])
# -> `concat` now has shape `(*, 25)`, as desired

但是 PyTorch 一直抱怨两层的大小不同:

# PyTorch — this does not work
class MyModel(torch.nn.Module):
    def __init__(self):
        self.layer1 = Embedding(50, 5)
        self.layer2 = Embedding(300, 20)

    def forward(self, inputs):
        layer_1 = self.layer1(inputs)
        layer_2 = self.layer2(inputs)
        concat = torch.cat([layer_1, layer_2])

上面的代码导致了这个错误:

RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 5 but got size 20 for tensor number 1 in the list.

我想要的最后 concat 层是由两个源层串联而成的 25 大小的层。

由于两个源层是 Embedding 层,我认为它们共享相同维度并不是最佳选择。在此示例中,对 50 项的词汇表使用 5 的嵌入维度,对 200 项的词汇表使用大小 20 的嵌入维度。

这个问题在PyTorch中应该如何解决?

实际上 torch.cat 将在第一个轴上应用串联。由于您希望在第二个轴上连接,因此您应该提供 dim 参数作为:

>>> concat = torch.cat([layer_1, layer_2], dim=1)