源自PyTorch 1.4教程
Outline
构建神经网络所需要的包可以是torch.nn
而nn包则依赖于autograd包来定义模型并对它们求导
今天写的是LeNet网络,用来识别手写体
数据集的选用可以用mnist,可参见pytorch实现mnist手写数字识别
包含初始化,前向传播,统计全连接层前输入的特征个数
网络执行过程:conv1–>maxpool–>conv2–>maxpool–>fc1–>fc2–>fc3
代码如下:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 输入图像channel:1;输出channel:6;5x5卷积核
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# 2x2 Max pooling
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# 如果是方阵,则可以只使用一个数字进行定义,树池为2*2矩阵
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
#变成一个1*num_flat_features(x)的张量
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
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)
super() 函数是用于调用父类的一个方法,即调用了nn.Module。
Conv2d
class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
最大池化
输出
Net(
(conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
清零所有参数的梯度缓存,然后进行随机梯度的反向传播:
net.zero_grad()
out.backward(torch.randn(1, 10))
#计算损失,使用均方误差损失函数
output = net(input)
target = torch.randn(10) # 本例子中使用模拟数据
target = target.view(1, -1) # 使目标值与数据值尺寸一致
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
#输出
tensor(0.9866, grad_fn=)
net.zero_grad() # 清零所有参数(parameter)的梯度缓存
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
loss.backward()
print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)
#输出
conv1.bias.grad before backward
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([-0.0003, 0.0005, -0.0140, 0.0026, 0.0057, -0.0056])
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
下节写如何训练一个图片分类器
欢迎批评指正,一起学习进步!!!