1、层和块
import torch
from torch import nn
from torch.nn import functional as F
#nn.Sequential定义了一种特殊的Module
#我们通过实例化nn.Sequential来构建我们的模型, 层的执行顺序是作为参数传递的
net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
X = torch.rand(2, 20)
net(X)
1、自定义块
简要总结一下每个块必须提供的基本功能:
将输入数据作为其前向传播函数的参数。
通过前向传播函数来生成输出。请注意,输出的形状可能与输入的形状不同。例如,我们上面模型中的第一个全连接的层接收一个20维的输入,但是返回一个维度为256的输出。
计算其输出关于输入的梯度,可通过其反向传播函数进行访问。通常这是自动发生的。
存储和访问前向传播计算所需的参数。
根据需要初始化模型参数。
'''
我们首先看一下前向传播函数,它以X作为输入, 计算带有激活函数的隐藏表示,并输出其未规范化的输出值。
在这个MLP实现中,两个层都是实例变量。 要了解这为什么是合理的,可以想象实例化两个多层感知机(net1和net2), 并根据不同的数据对它们进行训练。
当然,我们希望它们学到两种不同的模型。
'''
class MLP(nn.Module):
# 用模型参数声明层。
def __init__(self):
# 调用MLP的父类Module的构造函数来执行必要的初始化。
# 这样,在类实例化时也可以指定其他函数参数,例如模型参数params(稍后将介绍)
super().__init__()
#这里,我们声明两个全连接的层
self.hidden = nn.Linear(20, 256) # 1、隐藏层
self.out = nn.Linear(256, 10) # 2、输出层
# 定义模型的前向传播,即如何根据输入X返回所需的模型输出
def forward(self, X):
# 注意,这里我们使用ReLU的函数版本,其在nn.functional模块中定义。
return self.out(F.relu(self.hidden(X)))
#实例化多层感知机的层,然后在每次调用正向传播函数时调用这些层
net = MLP()
print(net(X))
2、顺序块
class MySequential(nn.Module):
def __init__(self, *args):
super().__init__()
for idx, module in enumerate(args):
# 这里,module是Module子类的一个实例。我们把它保存在'Module'类的成员
# 变量_modules中。_module的类型是OrderedDict
self._modules[str(idx)] = module
def forward(self, X):
# OrderedDict保证了按照成员添加的顺序遍历它们
for block in self._modules.values():
X = block(X)
return X
net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X)
3、 在前向传播函数中执行代码
class FixedHiddenMLP(nn.Module):
def __init__(self):
super().__init__()
# 不计算梯度的随机权重参数。因此其在训练期间保持不变
self.rand_weight = torch.rand((20, 20), requires_grad=False)
self.linear = nn.Linear(20, 20)
def forward(self, X):
X = self.linear(X)
# 使用创建的常量参数以及relu和mm函数
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 = FixedHiddenMLP()
net(X)
4、混合搭配各种组合块的方法
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)
2、参数管理
1、参数访问
首先关注具有单隐藏层的多层感知机
import torch
from torch import nn
#其中的参数 下标依次是 0 、1 、2
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
X = torch.rand(size=(2, 4))
net(X)
'''
我们从已有模型中访问参数。 当通过Sequential类定义模型时, 我们可以通过索引来访问模型的任意层。
这就像模型是一个列表一样,每层的参数都在其属性中。
如下所示,我们可以检查第二个全连接层的参数。
'''
#net[2] 指的是:nn.Linear(8, 1)
#state_dict 权重就是他的状态 就是常用的 w 和 b 参数
print(net[2].state_dict())
1、目标参数--访问某个具体的参数
print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)
'''
<class 'torch.nn.parameter.Parameter'>
Parameter containing:
tensor([0.0887], requires_grad=True)
tensor([0.0887])
'''
net[2].weight.grad == None #True
2、一次性访问所有参数
print(*[(name, param.shape) for name, param in net[0].named_parameters()])
print(*[(name, param.shape) for name, param in net.named_parameters()])
'''
('weight', torch.Size([8, 4])) ('bias', torch.Size([8]))
('0.weight', torch.Size([8, 4])) ('0.bias', torch.Size([8]))
('2.weight', torch.Size([1, 8])) ('2.bias', torch.Size([1]))
'''
net.state_dict()['2.bias'].data #tensor([0.0887])
3、从嵌套块收集参数
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):
# 在这里嵌套
net.add_module(f'block {i}', block1())
return net
rgnet = nn.Sequential(block2(), nn.Linear(4, 1))
rgnet(X)
'''
tensor([[0.2596],
[0.2596]], grad_fn=<AddmmBackward0>)
'''
#查看嵌套块是怎么工作的
#我们已经设计了网络,让我们看看它是如何组织的
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)
)
'''
#因为层是分层嵌套的,所以我们也可以像通过嵌套列表索引一样访问它们。
#下面,我们访问第一个主要的块中、第二个子块的第一层的偏置项。
rgnet[0][1][0].bias.data
#tensor([ 0.1999, -0.4073, -0.1200, -0.2033, -0.1573, 0.3546, -0.2141, -0.2483])
2、参数初始化
1、内置初始化
# 下面的代码将所有权重参数初始化为标准差为0.01的高斯随机变量, 且将偏置参数设置为0。
def init_normal(m):
#只修改Linear 类型的层
if type(m) == nn.Linear:
# normal_ 函数后面带下划线,表示这是一个替换函数,不会有返回值。直接在m上修改
nn.init.normal_(m.weight, mean=0, std=0.01)
nn.init.zeros_(m.bias) #偏差都置为0
#对所有net 里的layer 遍历 对其中所有的module 都调用init_normal 方法处理其中的参数
net.apply(init_normal)
#查看数据
net[0].weight.data[0], net[0].bias.data[0]
#(tensor([-0.0214, -0.0015, -0.0100, -0.0058]), tensor(0.))
#我们还可以将所有参数初始化为给定的常数,比如初始化为1
def init_constant(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
net.apply(init_constant)
net[0].weight.data[0], net[0].bias.data[0]
#(tensor([1., 1., 1., 1.]), tensor(0.))
#对某些块应用不同的初始化方法
def init_xavier(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
def init_42(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 42)
#net 里面都是模组。 所有都可以用apply这个方法
net[0].apply(init_xavier)
net[2].apply(init_42)
#打印
print(net[0].weight.data[0])
print(net[2].weight.data)
'''
tensor([ 0.5236, 0.0516, -0.3236, 0.3794])
tensor([[42., 42., 42., 42., 42., 42., 42., 42.]])
'''
2、自定义初始化
def my_init(m):
if type(m) == nn.Linear:
print("Init", *[(name, param.shape)
for name, param in m.named_parameters()][0])
nn.init.uniform_(m.weight, -10, 10)
'''这个语句好省力'''
m.weight.data *= m.weight.data.abs() >= 5
net.apply(my_init)
net[0].weight[:2]
'''
Init weight torch.Size([8, 4])
Init weight torch.Size([1, 8])
tensor([[5.4079, 9.3334, 5.0616, 8.3095],
[0.0000, 7.2788, -0.0000, -0.0000]], grad_fn=<SliceBackward0>)
'''
#我们始终可以直接设置参数。
net[0].weight.data[:] += 1
net[0].weight.data[0, 0] = 42
net[0].weight.data[0]
#tensor([42.0000, 10.3334, 6.0616, 9.3095])
3、参数绑定
# 我们需要给共享层一个名称,以便可以引用它的参数
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])
'''tensor([True, True, True, True, True, True, True, True])
tensor([True, True, True, True, True, True, True, True])'''
3、自定义层
1、不带参数的层
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() #可以让均值变成0
layer = CenteredLayer()
layer(torch.FloatTensor([1, 2, 3, 4, 5]))
#tensor([-2., -1., 0., 1., 2.]) 均值变成0 了
#现在,我们可以将层作为组件合并到更复杂的模型中。
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
'''作为额外的健全性检查,我们可以在向该网络发送随机数据后,检查均值是否为0。 由于我们处理的是浮点数,因为存储精度的原因,我们仍然可能会看到一个非常小的非零数。'''
Y = net(torch.rand(4, 8))
Y.mean()
#tensor(7.4506e-09, grad_fn=<MeanBackward0>)
2、带参数的图层
'''
下面我们继续定义具有参数的层, 这些参数可以通过训练进行调整。
我们可以使用内置函数来创建参数,这些函数提供一些基本的管理功能。 比如管理访问、初始化、共享、保存和加载模型参数。
这样做的好处之一是:我们不需要为每个自定义层编写自定义的序列化程序。
现在,让我们实现自定义版本的全连接层。
回想一下,该层需要两个参数,一个用于表示权重,另一个用于表示偏置项。
在此实现中,我们使用修正线性单元作为激活函数。
该层需要输入参数:in_units和units,分别表示输入数和输出数。
'''
class MyLinear(nn.Module):
def __init__(self, in_units, units):
super().__init__()
'''自定义参数的时候,要把参数包装一下放进 nn.Parameter 里面'''
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
return F.relu(linear)
linear = MyLinear(5, 3)
print(linear.weight)
'''
Parameter containing:
tensor([[ 0.1775, -1.4539, 0.3972],
[-0.1339, 0.5273, 1.3041],
[-0.3327, -0.2337, -0.6334],
[ 1.2076, -0.3937, 0.6851],
[-0.4716, 0.0894, -0.9195]], requires_grad=True)
'''
#我们可以使用自定义层直接执行前向传播计算。
#使用自定义层直接执行正向传播计算
linear(torch.rand(2, 5))
'''
tensor([[0., 0., 0.],
[0., 0., 0.]])
'''
#使用自定义层构建模型,就像使用内置的全连接层一样使用自定义层。
net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))
net(torch.rand(2, 64)) #tensor([[0.], [0.]])
4、读写文件--怎么存下训练好的东西
1、加载和保存张量
import torch
from torch import nn
from torch.nn import functional as F
x = torch.arange(4)
torch.save(x, 'x-file')
#可以将存储在文件中的数据读回内存。
x2 = torch.load('x-file')
print(x2) #tensor([0, 1, 2, 3])
#我们可以存储一个张量列表,然后把它们读回内存。
y = torch.zeros(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')
print((x2, y2)) #(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))
#可以写入或读取从字符串映射到张量的字典。 当我们要读取或写入模型中的所有权重时,这很方便。
mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
print(mydict2)
#{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}
2、加载和保存模型参数
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()
'''MLP(
(hidden): Linear(in_features=20, out_features=256, bias=True)
(output): Linear(in_features=256, out_features=10, bias=True)
)
'''
Y_clone = clone(X)
Y_clone == Y
'''
tensor([[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True]])
'''