技术标签: 深度学习 神经网络 深度学习(pytorch)
本文主要是学习了Dive-into-DL-PyTorch这本书。因此这篇博客的大部分内容来源于此书。框架使用的是pytorch,开发工具是pycharm
参考 动手学深度学习Dive-into-DL-Pytorch
参考链接 https://github.com/ShusenTang/Dive-into-DL-PyTorch
https://github.com/zergtant/pytorch-handbook
Module类是nn模块提供的一个模型构造类,是所有神经网络模块的基类,可以继承它来定义模型。
定义一个继承Module的类
import torch
from torch import nn
from collections import OrderedDict
class MLP(nn.Module): #在类中构造模型
#声明带有模型参数的层(这里声明了两个全连接层)
def __init__(self,**kwargs):
#调用MLP父类Block的构造函数来进行必要的初始化。这样在构造实例时还可以知道其他函数
super(MLP,self).__init__(**kwargs)
self.hidden = nn.Linear(784,256)#隐藏层
self.act = nn.ReLU() #激活函数
self.output = nn.Linear(256,10)#输出层
#定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出
def forward(self,x):
a = self.act(self.hidden(x))
return self.output(a)
X = torch.rand(2,784)
net = MLP()
print(net)
print(net.forward(X))
#print(net(X)) 调用前向传播函数
输出:
MLP(
(hidden): Linear(in_features=784, out_features=256, bias=True)
(act): ReLU()
(output): Linear(in_features=256, out_features=10, bias=True)
)
tensor([[ 0.2753, 0.0914, -0.0912, -0.2127, 0.0405, -0.0403, 0.0864, 0.1921,
-0.0172, 0.2593],
[ 0.2913, 0.2334, -0.0551, -0.1521, 0.1211, -0.0620, 0.1931, 0.1713,
-0.1314, 0.1571]], grad_fn=<AddmmBackward>)
可以接受一个子模块的有序字典(OrderedDict)或一系列子模块作为参数来注意添加Module的实例
# Sequential类
import torch
from torch import nn
from collections import OrderedDict
class MySequential(nn.Module): #定义构造模型的框架
from collections import OrderedDict
def __init__(self, *args):
super(MySequential, self).__init__()
if len(args) == 1 and isinstance(args[0], OrderedDict): # 如果传入的是一个OrderedDict
for key, module in args[0].items():
self.add_module(key, module) # add_module方法会将 module添加进self._modules(一个OrderedDict)
else: # 传入的是一些Module
for idx, module in enumerate(args):
self.add_module(str(idx), module)
def forward(self, input):
# self._modules返回一个OrderedDict,保证会按照成员添加时的顺序遍历
for module in self._modules.values():
input = module(input) #上一层的输出作为下一层的输入
return input
net = MySequential( #模型中添加相应的层
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10),
)
print(net)
X = torch.rand(2,784)
print(net(X))
输出
MySequential(
(0): Linear(in_features=784, out_features=256, bias=True)
(1): ReLU()
(2): Linear(in_features=256, out_features=10, bias=True)
)
tensor([[-0.1404, -0.1520, 0.1003, -0.3056, 0.1817, 0.2261, -0.0632, -0.0207,
0.1549, -0.0213],
[-0.2428, -0.0240, 0.0505, -0.2831, 0.1137, 0.2029, -0.0460, -0.0049,
0.1482, -0.0043]], grad_fn=<AddmmBackward>)
注:isinstance()函数是python内置函数,用来判断一个对象是否是一个已知的类型。
语法
isinstance(object, classinfo)
参数
object——实例对象
classinfo——可以是直接或间接类名、基本类型或者由他们组成的元组。
返回值
如果对象类型与参数二的类型(classinfo)相同则返回True,否则返回False。如果参数二是一个元组的话,只要对象类型是元组中的任意一个即返回True
ModuleList接收一个子模块的列表作为输入,然后也可以类似List那样进行append和extend操作
import torch
from torch import nn
from collections import OrderedDict
net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
net.append(nn.Linear(256, 10)) # # 类似List的append操作
print(net[-1]) #类似List的索引访问 输出模型的最后一层的参数
print(net)
输出
Linear(in_features=256, out_features=10, bias=True)
ModuleList(
(0): Linear(in_features=784, out_features=256, bias=True)
(1): ReLU()
(2): Linear(in_features=256, out_features=10, bias=True)
)
ModuleDict接收一个子模块的字典作为输入,然后也可以类似字典那样进行添加访问操作
import torch
from torch import nn
from collections import OrderedDict
net = nn.ModuleDict({
'linear': nn.Linear(784, 256),
'act': nn.ReLU(), })
net['output'] = nn.Linear(256, 10) # 添加
print(net['linear']) #访问
print(net.output)
print(net)
输出
Linear(in_features=784, out_features=256, bias=True)
Linear(in_features=256, out_features=10, bias=True)
ModuleDict(
(act): ReLU()
(linear): Linear(in_features=784, out_features=256, bias=True)
(output): Linear(in_features=256, out_features=10, bias=True)
)
import torch
from torch import nn
from collections import OrderedDict
class FancyMLP(nn.Module):
def __init__(self, **kwargs):
super(FancyMLP, self).__init__(**kwargs)
self.rand_weight = torch.rand((20, 20), requires_grad=False) # 不可训练参数
self.linear = nn.Linear(20, 20)
def forward(self, x):
x = self.linear(x)
# 使用创建的常数参数,以及nn.functional中的relu函数和mm函数
x = nn.functional.relu(torch.mm(x, self.rand_weight.data) + 1)
#复用全连接层。等价于两个全连接层共享参数
x = self.linear(x)
# 控制流,这里需要调用item函数来返回标量进行比较
while x.norm().item() > 1:
#x.norm返回的是2-范数(求出来的是一个标量--距离函数)
x /= 2
if x.norm().item() < 0.8:
x *= 10
return x.sum()
class NestMLP(nn.Module):
def __init__(self, **kwargs):
super(NestMLP, self).__init__(**kwargs)
self.net = nn.Sequential(nn.Linear(40, 30), nn.ReLU())
def forward(self, x):
return self.net(x)
#在Sequential中添加层,两个自定义层,一个线性层
net = nn.Sequential(NestMLP(), nn.Linear(30, 20), FancyMLP())
X = torch.rand(2, 40)
print(net) #打印网络结构
print(net(X))
输出
Linear(in_features=784, out_features=256, bias=True)
Linear(in_features=256, out_features=10, bias=True)
ModuleDict(
(act): ReLU()
(linear): Linear(in_features=784, out_features=256, bias=True)
(output): Linear(in_features=256, out_features=10, bias=True)
)
Sequential(
(0): NestMLP(
(net): Sequential(
(0): Linear(in_features=40, out_features=30, bias=True)
(1): ReLU()
)
)
(1): Linear(in_features=30, out_features=20, bias=True)
(2): FancyMLP(
(linear): Linear(in_features=20, out_features=20, bias=True)
)
)
tensor(-1.8696, grad_fn=<SumBackward0>)
注:
可以通过Module类的parameters()或者named_parameters方法访问所有参数(以迭代器的形式返回)后者除了返回参数Tensor外还会返回其名字
import torch
from torch import nn
from torch.nn import init
net = nn.Sequential(nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 1))
# pytorch已进行默认初始化
print(net)
X = torch.rand(2, 4)
Y = net(X).sum()
#访问模型参数
print(type(net.named_parameters()))
for name, param in net.named_parameters():
print(name, param.size())
#对于用Sequential类构造的神经网络,可通过方括号[]访问网络的任意一层
for name, param in net[0].named_parameters():
print(name, param.size(), type(param))
weight_0 = list(net[0].parameters())[0]
print(weight_0.data)
print(weight_0.grad) # 反向传播前梯度为None
Y.backward()
print(weight_0.grad)
结果
Sequential(
(0): Linear(in_features=4, out_features=3, bias=True)
(1): ReLU()
(2): Linear(in_features=3, out_features=1, bias=True)
)
<class 'generator'>
0.weight torch.Size([3, 4])
0.bias torch.Size([3])
2.weight torch.Size([1, 3])
2.bias torch.Size([1])
weight torch.Size([3, 4]) <class 'torch.nn.parameter.Parameter'>
bias torch.Size([3]) <class 'torch.nn.parameter.Parameter'>
tensor([[-0.3634, 0.1537, 0.0295, -0.1345],
[-0.0541, 0.1253, -0.2417, 0.1868],
[-0.1540, 0.4253, -0.0125, 0.3747]])
None
tensor([[ 0.0000, 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000],
[-0.3371, -0.3907, -0.1603, -0.3387]])
(1)通过init模块初始化
import torch
from torch import nn
from torch.nn import init
net = nn.Sequential(nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 1))
for name, param in net.named_parameters():
if 'weight' in name:
init.normal_(param, mean=0, std=0.01)
print(name, param.data)
for name, param in net.named_parameters():
if 'bias' in name:
init.constant_(param, val=0)
print(name, param.data)
输出:
0.weight tensor([[-0.0128, -0.0087, -0.0254, -0.0042],
[ 0.0165, 0.0082, 0.0122, -0.0097],
[-0.0245, -0.0023, -0.0160, -0.0036]])
2.weight tensor([[0.0111, 0.0175, 0.0039]])
0.bias tensor([0., 0., 0.])
2.bias tensor([0.])
(2)自定义初始化
'''
自定义的初始化方法,令权重有一半概率初始化为0,有另一半初始化为[-10,-5]和[5,10]
两个区间里均匀分布的随机数
'''
import torch
from torch import nn
from torch.nn import init
def init_weight_(tensor):
with torch.no_grad(): #该过程是不记录梯度的
tensor.uniform_(-10, 10) #均匀分布
tensor *= (tensor.abs() >= 5).float()
#tensor.abs() >= 5 返回的是bool类型的张量,(tensor.abs() >= 5).float()将bool类型转为float类型(0或1)
for name, param in net.named_parameters():
if 'weight' in name:
init_weight_(param)
print(name, param.data)
#可以通过改变这些参数的data来改写模型参数值同时不会影响梯度
for name, param in net.named_parameters():
if 'bias' in name:
param.data += 1
print(name, param.data)
输出结果与上面的代码的输出结果比较!
0.weight tensor([[ 6.7500, -0.0000, 0.0000, 0.0000],
[-0.0000, -0.0000, -8.1549, 0.0000],
[-0.0000, -0.0000, -9.7367, 0.0000]])
2.weight tensor([[ 7.3662, -5.8731, -0.0000]])
0.bias tensor([1., 1., 1.])
2.bias tensor([1.])
(1)在module类的forward函数中多次调用同一个层
(2)传入Sequential的模块是同一个module的实例的话参数也可以共享
import torch
from torch import nn
from torch.nn import init
linear = nn.Linear(1, 1, bias=False)
net = nn.Sequential(linear, linear)
print(net)
for name, param in net.named_parameters():
init.constant_(param, val=3)
print(name, param.data)
#在内存中,这两个线性层其实是一个对象
print(id(net[0]) == id(net[1])) #true
print(id(net[0].weight) == id(net[1].weight)) #true
#因为模型里包含了梯度,所以在反向传播时,这些共享的参数的梯度是累加的
#net:y=3x,y=3x 因为这两个线性层其实是一个对象,指向对一个内存空间,所以梯度会累加
x = torch.ones(1, 1)
y = net(x).sum()
print(y)
y.backward()
print(net[0].weight.grad) #单次梯度是3,两次所以就是6
结果
Sequential(
(0): Linear(in_features=1, out_features=1, bias=False)
(1): Linear(in_features=1, out_features=1, bias=False)
)
0.weight tensor([[3.]])
True
True
tensor(9., grad_fn=<SumBackward0>)
tensor([[6.]])
(1)不含模型参数的自定义层
import torch
from torch import nn
from torch.nn import init
class CenteredLayer(nn.Module):
def __init__(self, **kwargs):
super(CenteredLayer, self).__init__(**kwargs)
def forward(self, x):
return x - x.mean()
#实例化,然后做前向计算
layer = CenteredLayer()
out = layer(torch.tensor([1, 2, 3, 4, 5], dtype=torch.float))
print(out)
#构造更加复杂的模型
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
y = net(torch.rand(4, 8))
print(y.mean().item())
结果
tensor([-2., -1., 0., 1., 2.])
-2.7939677238464355e-09
(2)含模型参数的自定义层
自定义含模型参数的自定义层。其中的模型参数可通过训练得出
用Parameter类。如果一个Tensor是Parameter,那么它会自动被添加到模型的参数列表中。所以在自定义含模型参数的层时,应该将参数定义成Parameter.还可以使用ParameterList和ParameterDict分别定义参数的列表和字典。
ParameterList接收一个Parameter实例的列表作为输入得到一个参数列表,使用的时候可以用索引访问某个参数,也可以使用append和extend在列表后面新增参数。
ParameterDict接收一个Parameter实例的字典作为输入然后得到一个参数字典,然后按照字典的规则使用。使用update()新增参数,使用keys()返回所有键值,使用items()返回所有键值对等等。
import torch
from torch import nn
from torch.nn import init
class MyDense(nn.Module):
def __init__(self):
super(MyDense, self).__init__()
self.params = nn.ParameterList([nn.Parameter(torch.randn(4, 4)) for i in range(3)])
self.params.append(nn.Parameter(torch.randn(4, 1)))
def forward(self, x):
for i in range(len(self.params)):
x = torch.mm(x, self.params[i])
return x
net = MyDense()
print(net)
class MyDictDense(nn.Module):
def __init__(self):
super(MyDictDense, self).__init__()
self.params = nn.ParameterDict({
'linear1': nn.Parameter(torch.randn(4, 4)),
'linear2': nn.Parameter(torch.randn(4, 1))
})
self.params.update({
'linear3': nn.Parameter(torch.randn(4, 2))}) # 新增
def forward(self, x, choice='linear1'):
return torch.mm(x, self.params[choice])
net = MyDictDense()
print(net)
#使用自定义层构造模型
net = nn.Sequential(
MyDictDense(),
MyDense(),
)
print(net)
x = torch.rand(4, 4)
print(net(x))
结果
MyDense(
(params): ParameterList(
(0): Parameter containing: [torch.FloatTensor of size 4x4]
(1): Parameter containing: [torch.FloatTensor of size 4x4]
(2): Parameter containing: [torch.FloatTensor of size 4x4]
(3): Parameter containing: [torch.FloatTensor of size 4x1]
)
)
MyDictDense(
(params): ParameterDict(
(linear1): Parameter containing: [torch.FloatTensor of size 4x4]
(linear2): Parameter containing: [torch.FloatTensor of size 4x1]
(linear3): Parameter containing: [torch.FloatTensor of size 4x2]
)
)
Sequential(
(0): MyDictDense(
(params): ParameterDict(
(linear1): Parameter containing: [torch.FloatTensor of size 4x4]
(linear2): Parameter containing: [torch.FloatTensor of size 4x1]
(linear3): Parameter containing: [torch.FloatTensor of size 4x2]
)
)
(1): MyDense(
(params): ParameterList(
(0): Parameter containing: [torch.FloatTensor of size 4x4]
(1): Parameter containing: [torch.FloatTensor of size 4x4]
(2): Parameter containing: [torch.FloatTensor of size 4x4]
(3): Parameter containing: [torch.FloatTensor of size 4x1]
)
)
)
tensor([[-2.1693, 0.8641, 2.4579, 2.6433],
[-3.6363, 0.9381, 4.6731, 3.8805],
[-1.6930, 1.5060, 1.5372, 2.1564],
[-2.8876, 4.4967, 3.6148, 4.9272]], grad_fn=<MmBackward>)
文章浏览阅读645次。这个肯定是末尾的IDAT了,因为IDAT必须要满了才会开始一下个IDAT,这个明显就是末尾的IDAT了。,对应下面的create_head()代码。,对应下面的create_tail()代码。不要考虑爆破,我已经试了一下,太多情况了。题目来源:UNCTF。_攻防世界困难模式攻略图文
文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作 导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释: cwy_init/init_123..._达梦数据库导入导出
文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js
文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6
文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输
文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...
文章浏览阅读304次。Thinkpad X250笔记本电脑,装的是FreeBSD,进入BIOS修改虚拟化配置(其后可能是误设置了安全开机),保存退出后系统无法启动,显示:secure boot failed ,把自己惊出一身冷汗,因为这台笔记本刚好还没开始做备份.....根据错误提示,到bios里面去找相关配置,在Security里面找到了Secure Boot选项,发现果然被设置为Enabled,将其修改为Disabled ,再开机,终于正常启动了。_安装完系统提示secureboot failure
文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割
文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答
文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。
文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入
文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf