目录
- 1.pyTorch神经网络基础
- 层和块
- 参数管理:访问参数 参数初始化
- 自定义一个层 跟定义网络没有什么区别
- 读写文件,训练好的东西如何存储
- 2.使用和购买GPU
- 张量在GPU上的使用
- 神经网络在GPU上的使用
1.pyTorch神经网络基础
层和块
块(block)可以描述单个层、由多个层组成的组件或整个模型本身。 使用块进行抽象的一个好处是可以将一些块组合成更大的组件
#首先,回顾一下多层感知机
import torch
from torch import nn
from torch.nn import functional as F
# Sequential是 PyTorch 中用于构建神经网络的一种容器。它允许用户按顺序地将多个层组合在一起,构建神经网络模型
#便捷式
net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
X = torch.rand(2, 20)
net(X)
#Module(发音猫九) 可以认为,任意一个层和神经网络,它都应该是Module的子类
#自定义块
class MLP(nn.Module):
# 用模型参数声明层。这里,我们声明两个全连接的层
def __init__(self):
# 调用MLP的父类Module的构造函数来执行必要的初始化。
# 这样,在类实例化时也可以指定其他函数参数,例如模型参数params(稍后将介绍)
super().__init__()
self.hidden = nn.Linear(20, 256) # 隐藏层
self.out = nn.Linear(256, 10) # 输出层
# 定义模型的前向传播,即如何根据输入X返回所需的模型输出
def forward(self, X):
# 注意,这里我们使用ReLU的函数版本,其在nn.functional模块中定义。
return self.out(F.relu(self.hidden(X)))
#通过自定义类实现网络
net = MLP()
net(X)
#自定义Sequential 顺序块
class MySequential(nn.Module):
#*args是收集参数,相当于吧若干个参数打包成一个传入
def __init__(self, *args):
super().__init__()
#用于将传入的模块列表 args 中的每个模块添加到当前类的 _modules 成员变量block中
for block in args:
self._modules[block] = block
#方法接收一个输入张量 X,然后依次通过 _modules 中保存的各个模块来处理输入数据
def forward(self, X):
for block in self._modules.values():
X = block(X)
return X
#nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)这些类信息都放入了*args
net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X)
#在前向传播函数中执行代码 可以通过继承Module方法,可以Sequential方法,去灵活的定义网络模型和参数
class FixedHiddenMLP(nn.Module):
def __init__(self):
super().__init__()
#创建了一个大小为 (20, 20) 的随机张量,该张量的值在 [0, 1) 范围内,且不需要梯度
self.rand_weight = torch.rand((20,20),requires_grad=False)
self.liner = nn.Linear(20,20)
def forward(self, X):
X = self.liner(X)
#经过线性变换后的张量 X 与随机权重 rand_weight 相乘,并加上常数 1,然后通过 ReLU 激活函数进行非线性变换
X = F.relu(torch.mm(X,self.rand_weight)+1)
X = self.linear(x)
while X.abs().sum() > 1:
X /= 2
return X.sum()
net = MLP()
net(X)
#混合搭配各种组合块的方法
class NestMLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(20, 64), nn.ReLU(),
nn.Linear(64, 32), nn.ReLU())
self.linear = nn.Linear(32, 16)
def forward(self, X):
return self.linear(self.net(X))
chimera = nn.Sequential(NestMLP(), nn.Linear(16, 20), FixedHiddenMLP())
chimera(X)
参数管理:访问参数 参数初始化
import torch
from torch import nn
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
#创建了一个大小为 (2, 4) 的随机张量 X
X = torch.rand(size=(2, 4))
net(X)
#访问网络中的参数
#当通过Sequential类定义模型时, 我们可以通过索引来访问模型的任意层。
#这就像模型是一个列表一样,每层的参数都在其属性中。 如下所示,我们可以检查第二个全连接层的参数。
print(net[2].state_dict())#net[2]拿到的就好是nn.Linear(8, 1) state_dict() 用于返回模型的参数字典
#输出:
OrderedDict([('weight(权重)', tensor([[-0.0427, -0.2939, -0.1894, 0.0220, -0.1709, -0.1522, -0.0334, -0.2263]])), ('bias(偏移)', tensor([0.0887]))])
#访问具体参数
print(type(net[2].bias))#访问偏移类型
print(net[2].bias)#访问数据和梯度
print(net[2].bias.data)#访问数据
net[2].weight.grad == None #访问权重参数的梯度
#一次性访问所有参数
print(*[(name, param.shape) for name, param in net[0].named_parameters()])
print(*[(name, param.shape) for name, param in net.named_parameters()])
#另一种访问方式
net.state_dict()['2.bias'].data
#从嵌套块中访问参数
def block1():
return nn.Sequential(nn.Linear(4, 8), nn.ReLU(),
nn.Linear(8, 4), nn.ReLU())
def block2():
net = nn.Sequential()
for i in range(4):
# 在这里嵌套block2嵌套4个block1 add_module向模型中添加子模块
net.add_module(f'block {i}', block1())
return net
rgnet = nn.Sequential(block2(), nn.Linear(4, 1))
rgnet(X)
print(rgnet)#查看网络结构
Sequential(
(0): Sequential(
(block 0): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
(block 1): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
(block 2): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
(block 3): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
)
(1): Linear(in_features=4, out_features=1, bias=True)
)
#内置初始化
#首先调用内置的初始化器。下面的代码将所有权重参数初始化为标准差为0.01的高斯随机变量, 且将偏置参数设置为0。
def init_normal(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, mean=0, std=0.01)#nn.init.normal_ 函数来实现正态分布初始化 对其权重进行标准正态分布的初始化,均值为 0,标准差为 0.01。
nn.init.zeros_(m.bias)#偏置为0
net.apply(init_normal)#会对模型 net 中所有类型为 nn.Linear 的层应用 init_normal 函数,对其参数进行初始化
net[0].weight.data[0], net[0].bias.data[0]#访问网络参数
#我们还可以将所有参数初始化为给定的常数,比如初始化为1。
def init_constant(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)#nn.init.constant_ 它会将权重参数初始化为一个指定的常数值
nn.init.zeros_(m.bias)
net.apply(init_constant)
net[0].weight.data[0], net[0].bias.data[0]
#对应不同的块使用不同的初始化
def init_xavier(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)#它根据 Xavier初始化方法对权重进行初始化,该方法旨在使得每一层的输出方差保持一致
def init_42(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 42)
net[0].apply(init_xavier)
net[2].apply(init_42)
print(net[0].weight.data[0])
print(net[2].weight.data)
#参数绑定
#有时我们希望在多个层间共享参数: 我们可以定义一个稠密层,然后使用它的参数来设置另一个层的参数。
# 我们需要给共享层一个名称,以便可以引用它的参数
shared = nn.Linear(8, 8)
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(),
shared, nn.ReLU(),
shared, nn.ReLU(),
nn.Linear(8, 1))
net(X)
# 检查参数是否相同
print(net[2].weight.data[0] == net[4].weight.data[0])
net[2].weight.data[0, 0] = 100
# 确保它们实际上是同一个对象,而不只是有相同的值
print(net[2].weight.data[0] == net[4].weight.data[0])
自定义一个层 跟定义网络没有什么区别
#构造一个没有任何参数的自定义层
import torch
import torch.nn.functional as F
from torch import nn
class CenteredLayer(nn.Module):
def __init__(self):
super().__init__()
def forward(self, X):
return X - X.mean()
#向该层提供一些数据
layer = CenteredLayer()
layer(torch.FloatTensor([1, 2, 3, 4, 5]))
#将层作为组件合并到构建更复杂的模型中
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
#定义带参数的图层
class MyLinear(nn.Module):
def __init__(self, in_units, units):#in_units输入参数 units输出参数
super().__init__()
self.weight = nn.Parameter(torch.randn(in_units, units))
self.bias = nn.Parameter(torch.randn(units,))
def forward(self, X):
linear = torch.matmul(X, self.weight.data) + self.bias.data#matmul函数执行矩阵乘法
return F.relu(linear)
#使用带参数的图层构建模型
net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))
net(torch.rand(2, 64))
读写文件,训练好的东西如何存储
有时我们希望保存训练的模型, 以备将来在各种环境中使用(比如在部署中进行预测)。 此外,当运行一个耗时较长的训练过程时, 最佳的做法是定期保存中间结果, 以确保在服务器电源被不小心断掉时,我们不会损失几天的计算结果。 因此,现在是时候学习如何加载和存储权重向量和整个模型了。
import torch
from torch import nn
from torch.nn import functional as F
#单个张量
x = torch.arange(4)#个名为x的张量,其中包含从0到3的整数序列。
torch.save(x, 'x-file')#保存到x-file文件中
x2 = torch.load('x-file')#从文件中读取
#可以存储一个张量列表,然后把它们读回内存
y = torch.zeros(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')
#甚至可以写入或读取从字符串映射到张量的字典
mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
#加载和保存模型参数
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(20, 256)
self.output = nn.Linear(256, 10)
def forward(self, x):
return self.output(F.relu(self.hidden(x)))
net = MLP()
X = torch.randn(size=(2, 20))
Y = net(X)
#模型的参数存储在一个叫做“mlp.params”的文件中。
torch.save(net.state_dict(), 'mlp.params')
#读取模型参数:实例化原始多层感知机模型的一个备份,然后直接读取文件中的存储的参数
clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
clone.eval()#用于将模型设置为评估模式。模式下,在推理过程中不再使用 Dropout层,而是使用所有参数
2.使用和购买GPU
张量在GPU上的使用
nvidia-smi#查看GPU版本和cuda版本
#深度学习网络默认都是在CPU上的,使用GPU要指定
import torch
from torch import nn
torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1')#访问两个GPU 0 1
torch.cuda.device_count()#查询GPU数量
#定义了两个函数, 这两个函数允许我们在不存在所需所有GPU的情况下运行代码
#这个函数作用是返回一个GPU,没有返回CPU
def try_gpu(i=0): #@save
"""如果存在,则返回gpu(i),否则返回cpu()"""
if torch.cuda.device_count() >= i + 1:
return torch.device(f'cuda:{i}')
return torch.device('cpu')
#这个函数作用是返回所有GPU,没有返回CPU
def try_all_gpus(): #@save
"""返回所有可用的GPU,如果没有GPU,则返回[cpu(),]"""
devices = [torch.device(f'cuda:{i}')
for i in range(torch.cuda.device_count())]
return devices if devices else [torch.device('cpu')]
try_gpu()#输出:device(type='cuda', index=0
try_gpu(10)#输出:device(type='cpu') 没有编号10的GPU
try_all_gpus()#输出:device(type='cuda', index=0), device(type='cuda', index=1)
#查询张量所在的设备,一般默认在CPU
x = torch.tensor([1, 2, 3])
x.device#输出:device(type='cpu')
# 存储在GPU上
X = torch.ones(2, 3, device=try_gpu())
X#输出:tensor([[1., 1., 1.],[1., 1., 1.]], device='cuda:0')
#第二个GPU上创建一个随机张量
Y = torch.rand(2, 3, device=try_gpu(1))
Y#输出:tensor([[0.4860, 0.1285, 0.0440],[0.9743, 0.4159, 0.9979]], device='cuda:1')
#如果要计算X+Y,需要X和Y都在GPU上,同时要在同一张GPU上
人们使用GPU来进行机器学习,因为单个GPU相对运行速度快。 但是在设备(CPU、GPU和其他机器)之间传输数据比计算慢得多。 这也使得并行化变得更加困难,因为我们必须等待数据被发送(或者接收), 然后才能继续进行更多的操作。 这就是为什么拷贝操作要格外小心。
神经网络在GPU上的使用
#创建神经网络
net = nn.Sequential(nn.Linear(3, 1))
#把网络挪到某个GPU上
net = net.to(device=try_gpu())
net(X)
#确定模型参数存储在同一个GPU上
net[0].weight.data.device#输出:device(type='cuda', index=0)



















