%matplotlib
Using matplotlib backend: TkAgg
神经网络的典型训练过程如下:
1:定义包含一些参数(或者权重)的神经网络模型
2:在数据集上迭代,
3:通过神经网络处理输入
4:计算损失,输出值和正确值的插值大小
5:将梯度反向传播会回网络的参数
6:更新网络的参数,主要使用如下的更新原则:weight = weight - learning_rate * gradient
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module): #继承父类,nn.Module类
def __init__(self): #初始化函数
super(Net,self).__init__() #继承nn.Model类的初始化函数
# 1 input image channel, 6 output channels, 5x5 square convolution
# kernel 网络核心
self.conv1 = nn.Conv2d(1,6,5) # in_channels, out_channels, kernel_size(int or tuple)
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):
# 最大池(2,2)窗口
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) #这个好像是使用一个激活函数把每个层的结果输出,给下一个层
# 如果大小是正方形,只需指定一个数字
x = F.max_pool2d(F.relu(self.conv2(x)),2)
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):
print("size_x = ",x.size())
size = x.size()[1:] # 除batch维度外的所有维度
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
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)
)
在模型中必须定义forward函数,backwar函数(用来计算梯度)会被autograd自动创建。可以在forward使用任何针对Tensor的操作
net.parameters 返回可被学习的参数(权重)列表和值:
params = list(net.parameters())
# print(params)
print(len(params))
print(params[0].size())
10
torch.Size([6, 1, 5, 5])
测试随机输入的32 * 32,注:这个网络(LeNet)期望的输入值是32 * 32,如果使用mnister数据集来训练这个网络,请把图片大小调整为32 * 32:
input_data = torch.randn(1,1,32,32)
print(input_data)
out = net(input_data)
print(out)
tensor([[[[ 0.2102, -1.2333, 1.4202, ..., 1.0124, 0.4074, 3.0330],
[ 0.3036, 1.7646, 2.8376, ..., -0.3026, -0.2055, 0.4243],
[ 0.1221, -0.0080, -0.7630, ..., -0.0455, -0.6371, 1.2535],
...,
[-1.0048, 0.0904, 0.3890, ..., -1.1193, 1.0771, 0.5562],
[ 0.2873, 0.8678, 0.3266, ..., 0.0129, 0.2750, 1.9106],
[ 0.6888, -1.6345, -0.3339, ..., -0.2520, -0.0806, 1.4338]]]])
size_x = torch.Size([1, 16, 5, 5])
tensor([[-0.0910, 0.0196, 0.0079, 0.1561, 0.0658, 0.0062, -0.0428, 0.0484,
0.0107, 0.0918]], grad_fn=)
将所有参数的梯度缓存清零,然后进行随机梯度的反向传播:
net.zero_grad()
out.backward(torch.randn(1,10))
Note:
torch.nn
只支持小批量输入。整个 torch.nn
包都只支持小批量样本,而不支持单个样本。 例如,nn.Conv2d
接受一个4维的张量, 每一维分别是sSamples * nChannels * Height * Width(样本数*通道数*高*宽)
。 如果你有单个样本,只需使用 input.unsqueeze(0)
来添加其它的维数
在继续之前,我们回顾一下到目前为止用到的类。
回顾:
torch.Tensor:一个用过自动调用 backward()实现支持自动梯度计算的 多维数组 , 并且保存关于这个向量的梯度 w.r.t.
nn.Module:神经网络模块。封装参数、移动到GPU上运行、导出、加载等。
nn.Parameter:一种变量,当把它赋值给一个Module时,被 自动 地注册为一个参数。
autograd.Function:实现一个自动求导操作的前向和反向定义,每个变量操作至少创建一个函数节点,每一个Tensor的操作都回创建一个接到创建Tensor和 编码其历史 的函数的Function节点。
重点如下:
定义一个网络
处理输入,调用backword
还剩:
计算损失
更新网络权重
一个损失函数接收一对(out,target)作为输入,计算一个值计算网络的输出和目标值差多少;
output为网络的输出,target为实际值。
nn中包含许多损失函数。nn.MSELoss是一个比较简单的损失函数,他计算网络输出和目标值之间的均方误差。例如:
output = net(input_data)
target = torch.randn(10) # 随机值作为案例实际值
print("target: ",target)
print("target.size() = ", target.size())
target = target.view(1,-1) # 使target和output的shape相同,从(10*1)的size改成(1*10)
ceriterion = nn.MSELoss()
loss = ceriterion(output,target)
print(loss)
size_x = torch.Size([1, 16, 5, 5])
target: tensor([ 0.5733, 1.0459, 0.8443, 1.5380, 0.1492, -1.0543, 1.2273, 0.6478,
0.4526, 0.2121])
target.size() = torch.Size([10])
tensor(0.7417, grad_fn=)
为了说明,让我们向后退几步:
print(loss.grad_fn) #MSELoss
print(loss.grad_fn.next_functions[0][0]) # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) #Relu
调用loss.backward()来获取反向传播的误差; 但是在调用前需要清除已存的梯度,否则梯度将被累加到已存在的梯度 ; 现在我们将查看conv1层的偏差(bias)项在反向传播前后的梯度。
net.zero_grad #清除梯度
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.0008, 0.0065, 0.1106, 0.0193, 0.0636, -0.0238])
conv1.bias.grad after backward
tensor([-0.0052, 0.0265, 0.1005, 0.0274, 0.0595, -0.0207])
在实践中最简单的权重更新规则是随机梯度下降(SGD):
weight = weight - learning_rate * gradient
我们可以使用简单的Python代码实现这个规则:
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
但是当使用神经网络是想要使用各种不同的更新规则时,比如SGD、Nesterov-SGD、Adam、RMSPROP等,PyTorch中构建了一个包torch.optim实现了所有的这些规则。 使用它们非常简单:`
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(),lr=0.01)
#in your trainingg loop
optimizer.zero_grad() #zero the gradient buffers
out = net(input_data)
loss = ceriterion(out,target)
print("loss = ",loss)
loss.backward()
optimizer.step #does the update
size_x = torch.Size([1, 16, 5, 5])
loss = tensor(0.7417, grad_fn=)