多维张量上的感知器

Perceptron on multi-dimensional tensor

我正在尝试使用 Perceptron 将大小为 [1, 24, 768] 的张量减小为大小为 [1, 1, 768] 的另一个张量。我可以使用的唯一方法是首先将输入张量重塑为 [1, 1, 24*768],然后将其传递给线性层。我想知道是否有这种转换的更优雅的方式——除了使用 RNN,因为我不想使用它。我想进行的转换通常还有其他方法吗?这是我执行上述操作的代码:

lin = nn.Linear(24*768, 768)

# x is in shape of [1, 24, 768]
# out is in shape of [1, 1, 768]
x = x.view(1,1,-1)
out = lin(x)

如果广播让您感到困扰,您可以使用 nn.Flatten 来解决:

>>> m = nn.Sequential(
...    nn.Flatten(),
...    nn.Linear(24*768, 768))

>>> x = torch.rand(1, 24, 768)

>>> m(x).shape
torch.Size([1, 768])

如果你真的想要额外的维度,你可以解压缩 axis=1 上的张量:

>>> m(x).unsqueeze(1).shape
torch.Size([1, 1, 768])