1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| # PyTorch 神经网络构建指南
## 神经网络构建基础
PyTorch 使用 `torch.nn` 程序包构建神经网络: - 基于 `autograd` 定义和区分模型 - `nn.Module` 包含: - 多个网络层 - `forward(input)` 方法(返回输出)
## 案例1:定义网络
```python import torch import torch.nn as nn import torch.nn.functional as F
class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 定义网络层 self.conv1 = nn.Conv2d(1, 6, 3) # 1输入通道,6输出通道,3x3卷积核 self.conv2 = nn.Conv2d(6, 16, 3) # 6输入通道,16输出通道,3x3卷积核 self.fc1 = nn.Linear(16*6*6, 120) # 全连接层 (16*6*6 -> 120) self.fc2 = nn.Linear(120, 84) # 全连接层 (120 -> 84) self.fc3 = nn.Linear(84, 10) # 全连接层 (84 -> 10) def forward(self, x): # 前向传播 x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # 卷积+ReLU+2x2最大池化 x = F.max_pool2d(F.relu(self.conv2(x)), 2) # 卷积+ReLU+2x2最大池化 x = x.view(-1, self.num_flat_features(x)) # 展平 x = F.relu(self.fc1(x)) # 全连接+ReLU x = F.relu(self.fc2(x)) # 全连接+ReLU x = self.fc3(x) # 输出层 return x def num_flat_features(self, x): # 计算展平后的特征数量 size = x.size()[1:] # 除批量维度外的所有维度 num_features = 1 for s in size: num_features *= s return num_features
# 实例化网络 net = Net() print(net)
|