首页 > 解决方案 > pytorch线性方法中的多维输入?

问题描述

在构建简单的感知器神经网络时,我们通常将输入格式的二维矩阵传递给二维权(batch_size,features)重矩阵,类似于numpy中的简单神经网络。我一直假设神经网络的感知器/密集/线性层只接受 2D 格式的输入并输出另一个 2D 输出。但最近我遇到了这个 pytorch 模型,其中一个线性层接受一个 3D 输入张量并输出另一个 3D 张量 ( o1 = self.a1(x))。

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.a1 = nn.Linear(4,4)
        self.a2 = nn.Linear(4,4)
        self.a3 = nn.Linear(9,1)
    def forward(self,x):
        o1 = self.a1(x)
        o2 = self.a2(x).transpose(1,2)
        output = torch.bmm(o1,o2)
        output = output.view(len(x),9)
        output = self.a3(output)
        return output

x = torch.randn(10,3,4)
y = torch.ones(10,1)

net = Net()

criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters())

for i in range(10):
    net.zero_grad()
    output = net(x)
    loss = criterion(output,y)
    loss.backward()
    optimizer.step()
    print(loss.item())

这些是我的问题,

  1. 上面的神经网络是有效的吗?那就是模型是否会正确训练?
  2. 即使通过 3D 输入x = torch.randn(10,3,4),为什么 pytorchnn.Linear没有显示任何错误并给出 3D 输出?

标签: neural-networkdeep-learningpytorchperceptron

解决方案


较新版本的 PyTorch 允许nn.Linear接受 ND 输入张量,唯一的限制是输入张量的最后一个维度将等于in_features线性层。然后将线性变换应用于张量的最后一维。
例如,如果in_features=5输入out_features=10张量x的尺寸为 2-3-5,则输出张量的尺寸为 2-3-10。


推荐阅读