官网
1.要点:
** a method forward(input)that returns the output。**
You just have to define the forward function, and the backward function (where gradients are computed) is automatically defined for you using autograd.(我们定义的是前向传播的网络)
2.样例定义的网络:
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 = Net() :实例化定义的网络。
print(net)的结果:
模型合理性分析:
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
这段代码,conv1表明输出的深度变为原来6倍。所以在进行conv2的时候,通道数变为了6倍。
第一个参数是由上一层的输入决定的,决定的是卷积核的深度。
第二个参数是由自己定义的,决定是输出的深度。
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)
线性层同理。
3.可训练的参数:
实例化之后使用parameters()函数,
net = Net()
params = list(net.parameters())
print(len(params))
print(params[0].size())
print(params[1].size())
输出:
为什么是10呢?
2层卷积层,3层线性层。激活函数池化都没有,5个啊!
根据结果我判断是每一层网络都有一个权重和一个偏执项作为可训练的参数,所以最后乘2.
4.池化过程矩阵变化:只是改变最后两个。
m = torch.nn.MaxPool2d(3, stride=2)
input = autograd.Variable(torch.randn(20, 16, 50))
print(input.shape)
output = m(input)
output.shape
torch.Size([20, 16, 50])
torch.Size([20, 7, 24])
m = torch.nn.MaxPool2d((2,4), stride=2)
input = autograd.Variable(torch.randn(20, 16, 50))
print(input.shape)
output = m(input)
output.shape
torch.Size([20, 16, 50])
torch.Size([20, 8, 24])
池化时应该不改变维度的大小,只改变最后两个,由核的大小,和步长共同决定。
5.网络中涉及到的矩阵维度变化的具体的分析:
初始:(1, 1, 32, 32)
第一层中的卷积:
self.conv1 = nn.Conv2d(1, 6, 3)
1:通道 6:卷积核的个数。 3:卷积核的大小,步长为1.
x = F.relu(self.conv1(x))
结果:torch.Size([1, 6, 30, 30])
总结:倒数第三个参数由卷积核的个数决定,最后两个由步长和卷积核的大小决定。
第一层之后的池化:
x = F.max_pool2d(F.relu(self.conv1(x)), 2)
结果:torch.Size([1, 6, 15, 15])
这里有些困惑,难道池化默认不允许每次提取的重合,我觉得有道理:因为池化本来就是为了减少参数的数量。
之后的第二次卷积核池化同理:
self.conv2 = nn.Conv2d(6, 16, 3)
x = F.relu(self.conv2(x))
结果:torch.Size([1, 16, 13, 13])
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
结果:torch.Size([1, 16, 6, 6])
专门写了一个拉直的函数,拉直的目的是为了将其变成二维的,拉直的方式则是把第二维以及其后边的全部变成第二维度的内容了,因为第一维一般指的是样本的个数。:
拉直后:torch.Size([1, 576])
和这个区分:
a = torch.tensor([1, 2, 3])
print(a.shape)
torch.Size([3])
拉直代码:
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
6.view:
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
a = a.view(-1, 6)
print(a.shape)
import torch.nn as nn
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
a = a.view(-1)
print(a.shape)
7.Zero the gradient buffers of all parameters and backprops with random gradients:
一般不是随机,我遇到的代码是这样的:
、net.zero_grad()
out.backward(torch.randn(1, 10))
8.torch.nn只适合处理小批次的数据
torch.nn only supports mini-batches. The entire torch.nn package only supports inputs that are a mini-batch of samples, and not a single sample.
9.4D Tensor的一个理解:
nSamples x nChannels x Height x Width
在图片领域是这样理解的。
10.LOSS:
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)
MSELoss:
应该是相加 然后除以总数。
而且貌似和维度无关:
好像只要给定相同的维度,然后就会对相应位置的进行求差再求平方和。
22.而且是有方法提供求loss的计算图过程的:
23.backpropagate
net.zero_grad()的原因:
To backpropagate the error all we have to do is to loss.backward(). You need to clear the existing gradients though, else gradients will be accumulated to existing gradients.
代码:
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)
24.Update the weights:
使用优化器优化lr,以优化寻找最优解的过程:
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
optimizer.zero_grad().:也有这一步。
Observe how gradient buffers had to be manually set to zero using optimizer.zero_grad(). This is because gradients are accumulated as explained in the Backprop section.