pytorch构建前向传播神经网络
2021-02-02 本文已影响0人
羽天驿
# 使用pytorch构建一个前向传播得神经网络
import torch.nn as nn
import torch.nn.functional as F
# 定义前向传播网络
# 接收输入,经过层层得计算得到输出
# A定义模型得网络必须是继承父类nn.Model得网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 定义卷积层
self.conv1 = nn.Conv2d(1, 6, 5)
# 上述表示为图片单通道,6表示图片得输出通道数量,5表示卷积核为5*5
# 卷积层
self.conv2 = nn.Conv2d(6, 16, 5)
# 全连接层
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def format(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(x.size()[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self(self.fc3(x))
return x
net = Net()
print(net)
![](https://img.haomeiwen.com/i4956968/7442019819e50857.png)