神经网络
神经网络
神经网络可以用torch.nn这个包来创建。nn依赖于autograd来定义模型和求导,一个nn.Module包含layers(层),和一个可以返回output的方法——forward(input)
这是一个分类字母的分类网络。
一个典型的神经网络的训练过程如下:
- 定义一个包含可学习参数(如weights)的神经网络
- 迭代输入数据(input)
- 通过网络处理数据
- 计算loss
- 把梯度反向传播到参数中
- 更新可学习参数,通常用:weight = weight - learning_rate * gradient
定义一个网络
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 3x3 square convolution kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
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):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
输出:
Net(
(conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
(fc1): Linear(in_features=576, 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函数,backward函数因为你用autograd,所以是自动定义好的。你可以在forward函数中使用任何关于tensor的操作。使用net.parameters()可以返回模型中的可学习参数。
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
输出:
10
torch.Size([6, 1, 3, 3])
现在用3232的输入来试试(这个网络只能是3232)
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
把梯度缓存都清零,然后用随即的梯度值来进行后向传播:
net.zero_grad()
out.backward(torch.randn(1, 10))
注意:
torch.nn只支持mini-batches,不支持单张图片,conv2d接收的只能是4维的参数——nSamples x nChannels x Height x Width。如果是单张图片,就用input.unsqueeze(0)来增加一个维度。
还有就是坑爹的官网竟然是错的,全连接层图里面显示的是1655,代码里写的是in_features=576
,也就是说1666,我是把代码里的params
一个个打印出来看的,然后对着这个图一一对着看,才发现不对。
这个params
长度为10,里面的参数的shape
分别为
- torch.Size([6, 1, 3, 3])6个卷积核,每个深度是1,长宽都是3。
- torch.Size([6])6个偏置值,第一个卷积操作的可学习参数都出来了。
- torch.Size([16, 6, 3, 3])16个卷积核,深度(维度)是6,高宽为3。
- torch.Size([16])16个偏置值,第二个卷积操作的可学习参数也出来了。
- torch.Size([120, 576])120个卷积核,每个卷积核深度16,高宽为6,1666=576。我就是在这发现图标注错了的。这里有点不一样,就是没写成刚刚卷积操作的那种四个维度,而是显示的是两个维度,一个输出维度数,剩下的组成一个维度。
- torch.Size([120])第一个全连接的120个偏置值。
- torch.Size([84, 120])第二个全连接操作的卷积核,输入120,输出84,所以相当于84个卷积核,每个卷积核深度84,高宽都是1.
- torch.Size([84])第二个全连接操作的84个偏置值。
- torch.Size([10, 84])最后一个全连接操作,输入84,输出10,相当于10个卷积核,每个卷积核深度84,高宽都是1.
- torch.Size([10])最后的10个偏置值。
现在,刚刚定义的这个模型的所有可学习参数都在上面列出来了。
小结
- torch.Tensor:一个支持.backward()这类自动操作的多为数组,同时也保存tensor的梯度值。
- nn.Module:神经网络模型,可以方便的压缩参数,放到GPU上,传递和加载参数等等。
- nn.Parameter:是一个tensor,当它作为属性被分配给Module的时候,它就自动注册成一个参数了
- autograd.Function:使autograd的前向后向操作的定义生效,每一个对于tensor的操作都会创建至少一个连接到创建tensor操作的Function节点,并且记录它的历史。
Loss Function损失函数
A loss function takes the (output, target) pair of inputs, and computes a value that estimates how far away the output is from the target.
There are several different loss functions under the nn package . A simple loss is: nn.MSELoss which computes the mean-squared error between the input and the target.
损失函数接收输出和真值作为它的输入,计算出output离目标真值差多少,nn包中有很多损失函数,MSE是其中一个。
output = net(input)
target = torch.randn(10) # a dummy target, for example
target = target.view(1, -1) # make it the same shape as output
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
如果你跟着loss的后向传播,用.grad_fn属性,你就可以看到像这样的计算图:
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
因此,当我们调用loss.vackward(),整个计算图开始计算梯度,所有requires_grad=True的tensor的.grad属性中都开始累计各自的梯度。
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
输出:
<MseLossBackward object at 0x7f32f4af25c0>
<AddmmBackward object at 0x7f32f4af25f8>
<AccumulateGrad object at 0x7f32f4af25f8>
后向传播
开始后向传播,我们只需要loss.backward()。当然,我们也要将梯度清零,负责新计算的梯度就会累积在原来梯度上。
现在来看看conv1的bias的梯度在后向传播前后的变化:
net.zero_grad() # zeroes the gradient buffers of all parameters
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.0068, -0.0244, 0.0278, -0.0142, 0.0111, -0.0078])
Update the weights更新权重参数值
最简单的方法是Stochastic Gradient Descent (SGD):随即梯度下降
weight = weight - learning_rate * gradient
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
但是想用不同的rules怎么办,于是就有了torch.optim包。
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)
# in your training loop:
optimizer.zero_grad() # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # Does the update