Pytorch学习笔记(二)---- 神经网络搭建

记录如何用Pytorch搭建LeNet-5,大体步骤包括:网络的搭建->前向传播->定义Loss和Optimizer->训练

# -*- coding: utf-8 -*-
# All codes and comments from <<深度学习框架Pytorch入门与实践>>
# Code url : https://github.com/zhouzhoujack/pytorch-book
# lesson_2 : Neural network of PT(Pytorch)

# torch.nn是专门为神经网络设计的模块化接口,nn构建于 Autograd之上,可用来定义和运行神经网络
# 定义网络时,需要继承nn.Module,并实现它的forward方法,把网络中具有可学习参数的层放在构造函数__init__中
# 下面是LeNet-5网络结构

import torch as t
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        # nn.Module子类的函数必须在构造函数中执行父类的构造函数
        # 下式等价于nn.Module.__init__(self)
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 5)             # 卷积层'1'表示输入图片为单通道, '6'表示输出通道数,'5'表示卷积核为5*5
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(in_features=16 * 5 * 5, out_features=120, bias=True)       # 全连接层,y = x*transposition(A) + b
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = F.max_pool2d(input=F.relu(self.conv1(x)), kernel_size=(2, 2))        # 卷积 -> 激活 -> 池化
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        # view函数只能由于contiguous的张量上,就是在内存中连续存储的张量,当tensor之前调用了transpose,
        # permute函数就会是tensor内存中变得不再连续,就不能调用view函数。
        # tensor.view() = np.reshape()
        x = x.view(x.size()[0], -1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
"""
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 = Net()

# 网络的可学习参数通过net.parameters()返回,net.named_parameters可同时返回可学习的参数及名称
"""
conv1.weight : torch.Size([6, 1, 5, 5])
conv1.bias : torch.Size([6])
conv2.weight : torch.Size([16, 6, 5, 5])
conv2.bias : torch.Size([16])
fc1.weight : torch.Size([120, 400])
fc1.bias : torch.Size([120])
fc2.weight : torch.Size([84, 120])
fc2.bias : torch.Size([84])
fc3.weight : torch.Size([10, 84])
fc3.bias : torch.Size([10])
"""
# parameters infomation of network
# params = list(net.parameters())
# for name,parameters in net.named_parameters():
#     print(name,':',parameters.size())

if __name__ == '__main__':
    """
    计算图如下:
    input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d  
          -> view -> linear -> relu -> linear -> relu -> linear 
          -> MSELoss
          -> loss

    """
    input = t.randn(1, 1, 32, 32)
    output = net(input)
    # >>torch.arange(1., 4.)
    # >>1 2 3 [torch.FloatTensor of size 3]
    # if missing . , the type of torch will change to int
    target = t.arange(0., 10.).view(1, 10)
    criterion = nn.MSELoss()
    loss = criterion(output, target)
    print(loss)

    # 运行.backward,观察调用之前和调用之后的grad
    net.zero_grad()  # 把net中所有可学习参数的梯度清零
    print('反向传播之前 conv1.bias的梯度')
    print(net.conv1.bias.grad)
    loss.backward()
    print('反向传播之后 conv1.bias的梯度')
    print(net.conv1.bias.grad)

    # Optimizer
    # torch.optim中实现了深度学习中绝大多数的优化方法,例如RMSProp、Adam、SGD等
    # 在反向传播计算完所有参数的梯度后,还需要使用优化方法来更新网络的权重和参数,例如随机梯度下降法(SGD)的更新策略如下:
    # weight = weight - learning_rate * gradient
    optimizer = optim.SGD(net.parameters(), lr=0.01)
    # 在训练过程中
    # 先梯度清零(与net.zero_grad()效果一样)
    optimizer.zero_grad()
    # 计算损失
    output = net(input)
    loss = criterion(output, target)
    # 反向传播
    loss.backward()
    # 更新参数
    optimizer.step()

nn.Conv2d()详解

torch.nn.Conv2d(in_channels,    # input channels
                out_channels,   # output channels
                kernel_size,    # conv kernel size
                stride=1,       
                padding=0,      # add the number of zeros per dimension
                dilation=1, 
                groups=1, 
                bias=True       # default=True
               )

其中Conv2d 的输入 input 尺寸为《Pytorch学习笔记(二)---- 神经网络搭建》
,输出 output 尺寸为《Pytorch学习笔记(二)---- 神经网络搭建》

《Pytorch学习笔记(二)---- 神经网络搭建》

Feature Map 大小计算

Size of Feature Map = (W – F + 2P)/S + 1

W : 输入图像尺寸宽度

F : 卷积核宽度

P:边界填充0数量

S:滑动步长

例如:

输入(227,227,3)

卷积层 kernel_size = 11

stride = 4

padding = 0

n(卷积核数量) = 96

输出 (55,55,96)

(227 – 11 + 0) /4 +1 = 55

参考资料

nn.Conv2d()详解:https://www.aiuai.cn/aifarm618.html

    原文作者:pytorch
    原文地址: https://www.cnblogs.com/huxiaozhouzhou/p/10615761.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞