neural-network - 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())
这些是我的问题,
- 上面的神经网络是有效的吗?那就是模型是否会正确训练?
- 即使通过 3D 输入
x = torch.randn(10,3,4)
,为什么 pytorchnn.Linear
没有显示任何错误并给出 3D 输出?
解决方案
较新版本的 PyTorch 允许nn.Linear
接受 ND 输入张量,唯一的限制是输入张量的最后一个维度将等于in_features
线性层。然后将线性变换应用于张量的最后一维。
例如,如果in_features=5
输入out_features=10
张量x
的尺寸为 2-3-5,则输出张量的尺寸为 2-3-10。
推荐阅读
- git - 如何将 Unity3D 项目中的 SteamVR 资产添加到版本控制?
- java - 如何在没有模块的情况下升级到 Java 11?
- java - 如果 array 或 arrayList 引用前一个元素,我如何实现一个函数以返回 true?
- javascript - 如何防止客户端刷新页面?
- reactjs - React 组件可以渲染存储在其状态中的另一个组件吗?
- exact-online - 为 Exact Online 从 PHP 客户端库更新记录
- angular - Angular 7 - 访问服务返回未定义的 observable
- unity3d - Unity3d - 碰撞功能跳跃
- haskell - 如何优化并行排序以提高时间性能?
- c - 将 char [] 附加到 char* content = realloc(NULL, sizeof(char) * 10);