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 尺寸为
,输出 output 尺寸为
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学习笔记(二)---- 神经网络搭建的更多相关文章
- 莫烦pytorch学习笔记(二)——variable
.简介 torch.autograd.Variable是Autograd的核心类,它封装了Tensor,并整合了反向传播的相关实现 Variable和tensor的区别和联系 Variable是篮子, ...
- 莫烦 - Pytorch学习笔记 [ 二 ] CNN ( 1 )
CNN原理和结构 观点提出 关于照片的三种观点引出了CNN的作用. 局部性:某一特征只出现在一张image的局部位置中. 相同性: 同一特征重复出现.例如鸟的羽毛. 不变性:subsampling下图 ...
- Mybatis-Plus 实战完整学习笔记(二)------环境搭建
第二章 使用实例 1.搭建测试数据库 -- 创建库 CREATE DATABASE mp; -- 使用库 USE mp; -- 创建表 CREATE TABLE tbl_employee( ...
- kvm虚拟化学习笔记(二)之linux kvm虚拟机安装
KVM虚拟化学习笔记系列文章列表----------------------------------------kvm虚拟化学习笔记(一)之kvm虚拟化环境安装http://koumm.blog.51 ...
- ZooKeeper学习笔记二:API基本使用
Grey ZooKeeper学习笔记二:API基本使用 准备工作 搭建一个zk集群,参考ZooKeeper学习笔记一:集群搭建. 确保项目可以访问集群的每个节点 新建一个基于jdk1.8的maven项 ...
- WPF的Binding学习笔记(二)
原文: http://www.cnblogs.com/pasoraku/archive/2012/10/25/2738428.htmlWPF的Binding学习笔记(二) 上次学了点点Binding的 ...
- AJax 学习笔记二(onreadystatechange的作用)
AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...
- [Firefly引擎][学习笔记二][已完结]卡牌游戏开发模型的设计
源地址:http://bbs.9miao.com/thread-44603-1-1.html 在此补充一下Socket的验证机制:socket登陆验证.会采用session会话超时的机制做心跳接口验证 ...
- JMX学习笔记(二)-Notification
Notification通知,也可理解为消息,有通知,必然有发送通知的广播,JMX这里采用了一种订阅的方式,类似于观察者模式,注册一个观察者到广播里,当有通知时,广播通过调用观察者,逐一通知. 这里写 ...
- Docker学习笔记之一,搭建一个JAVA Tomcat运行环境
Docker学习笔记之一,搭建一个JAVA Tomcat运行环境 前言 Docker旨在提供一种应用程序的自动化部署解决方案,在 Linux 系统上迅速创建一个容器(轻量级虚拟机)并部署和运行应用程序 ...
随机推荐
- 分布式存储ceph——(5)ceph osd故障硬盘更换
正常状态:
- WordPress慢的八种解决方法(用排查法解决)
WordPress的打开速度慢会影响到用户体验和关键词的稳定排名,WordPress为什么加载慢呢?其实很简单的,就是WordPress水土不服,用WordPress的大家都知道,WordPress是 ...
- sudo: no tty present and no askpass program specified
sudo: no tty present and no askpass program specified | 学步园 https://www.xuebuyuan.com/2157339.html 通 ...
- vue前端开发。。。
1. 官网下载 https://nodejs.org/en/ 2. 安装cnpm 在命令行: npm install -g cnpm --registry=https://registry.np ...
- 搭建一个MP-demo(mybatis_plus)
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发.提高效率而生. 搭建一个简单的MP-demo 1.配置pom.xml ...
- apache+php项目部署
先安装apache和php然后进行如下操作(以63服务器的安装路径为例) 1.查看php项目运行的报错信息 路径: cd /var/log/httpd/error_log 如果错误如下: 可以尝试 ...
- ILRuntime_NewbieGuide—导读
Welcome to the ILRuntime_NewbieGuide wiki! 入门篇:做个简单的案例 https://www.cnblogs.com/kerven/p/10237280.htm ...
- ezdxf包下autocad的开发
利用 ezdxf 库读写geotiff格式的地形影像方法(InsertRasterToCAD) 包一:dxfgrabber GitHub - mozman/dxfgrabber: Outdated D ...
- 「FHQ Treap」学习笔记
话说天下大事,就像fhq treap —— 分久必合,合久必分 简单讲一讲.非旋treap主要依靠分裂和合并来实现操作.(递归,不维护fa不维护cnt) 合并的前提是两棵树的权值满足一边的最大的比另一 ...
- js手机滑块模仿
点击文本框滑动选值 手机屏幕上的上下翻滚菜单使用JS实现.经过十几个小时的折磨,终于有了最初版本.实现办法如下描述: 一.要求和方法 1.一个input输入框,点击后弹出一个翻滚菜单盖在其上,翻滚选好 ...