技术标签: 深度学习 神经网络 深度学习(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>)
文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib
文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang
文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些
文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器
文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距
文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器
文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn
文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios
文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql
文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...
文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120
文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数