一、定义
1、块(block)可以描述单个层、由多个层组成的组件或整个模型本身。 使用块便于将一些块组合成更大的组件。
2、从编程的角度来看,块由类(class)表示。 它的任何子类都必须定义一个将其输入转换为输出的前向传播函数, 并且必须存储任何必需的参数。为了计算梯度,块必须具有反向传播函数,但反向传播我们使用自动求导,我们只需要考虑前向传播函数和必需的参数。
3、实例化nn.Sequential
来构建我们的模型, 层的执行顺序是作为参数传递的;nn.Sequential
定义了一种特殊的Module
, 即在PyTorch中表示一个块的类, 它维护了一个由Module(这个里面是层)
组成的有序列表。
net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
4、块的功能
(1)将输入数据作为其前向传播函数的参数。
(2)通过前向传播函数来生成输出。请注意,输出的形状可能与输入的形状不同。例如,我们上面模型中的第一个全连接的层接收一个20维的输入,但是返回一个维度为256的输出。
(3)计算其输出关于输入的梯度,可通过其反向传播函数进行访问。通常这是自动发生的。
(4)存储和访问前向传播计算所需的参数。
(5)根据需要初始化模型参数。
二、层与块
1、自定义块:从零开始编写一个块。,它包含一个多层感知机
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模块中定义。 #个人理解,先x输入进入隐藏层,然后进行relu,然后进行输出层 return self.out(F.relu(self.hidden(X)))
2、顺序块
class MySequential(nn.Module): #就像之前一样,传入我们所需的层 def __init__(self, *args): super().__init__() #idx是一个整数变量,表示当前循环迭代中的模块的索引位置,从0开始递增 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
3、在前向传播函数中执行代码:在这个FixedHiddenMLP
模型中,实现了一个隐藏层,权重不是一个模型参数,因此它永远不会被反向传播更新,神经网络将这个固定层的输出通过一个全连接层。
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函数 #relu(xw+b) X = F.relu(torch.mm(X, self.rand_weight) + 1) # 复用全连接层。这相当于两个全连接层共享参数 X = self.linear(X) # 控制流,将x的值逐步缩小,直到其绝对值之和不超过1 while X.abs().sum() > 1: X /= 2 return X.sum()
三、参数管理
1、参数访问
(1)检查第二个全连接层的参数:
print(net[2].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]))])
(2)访问底层的数值
#第一个parameter是模块,第二个parameter是指可以优化的参数 print(type(net[2].bias)) -><class 'torch.nn.parameter.Parameter'> print(net[2].bias) ->Parameter containing:tensor([0.0887], requires_grad=True) print(net[2].bias.data) ->tensor([0.0887])
(3)一次性访问所有参数
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]))
(4)访问其他参数
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)) 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) )
四、参数初始化
1、内置初始化
(1)所有权重参数初始化为标准差为0.01的高斯随机变量, 将偏置参数设置为0
def init_normal(m): if type(m) == nn.Linear: #带下划线是替换函数,会将第一个参数(m.weight)替换掉 nn.init.normal_(m.weight, mean=0, std=0.01) nn.init.zeros_(m.bias) #apply就是接收一个函数,对立面的每个元素都用这个函数执行一遍,apply函数可以对所有层进行操作。 net.apply(init_normal) net[0].weight.data[0], net[0].bias.data[0]
(2)将所有参数初始化为给定的常数,比如初始化为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]
(3)使用Xavier初始化方法初始化第一个神经网络层
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[0].apply(init_xavier) net[2].apply(init_42) print(net[0].weight.data[0]) print(net[2].weight.data)
(4)对不同的层可以使用不同的初始化函数,适应要求
2、自定义初始化
def my_init(m): if type(m) == nn.Linear: #输出第一个线性层的权重参数的名称和形状 print("Init", *[(name, param.shape)for name, param in m.named_parameters()][0]) #线性层的权重进行均匀分布初始化,从区间 [−10,10] 的均匀分布中随机抽取的值 nn.init.uniform_(m.weight, -10, 10) #保留绝对值大于5的元素,不大于5就设为(先计算m.weight.data.abs() >= 5生成bool类型的0、1,然后m.weight.data做*=运算) m.weight.data *= m.weight.data.abs() >= 5 net.apply(my_init) net[0].weight[:2]#对模型net中第一个线性层的前两个权重的访问
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])
输出值会为true
五、自定义层
1、不带参数的层
class CenteredLayer(nn.Module): def __init__(self): super().__init__() def forward(self, X): #使其均值为0 return X - X.mean()
2、带参数的层
class MyLinear(nn.Module): def __init__(self, in_units, units): super().__init__() #in_units和units分别表示输入数和输出数 self.weight = nn.Parameter(torch.randn(in_units, units)) #(units,)是一个长度为1的元组 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)
#可以使用自定义层构建模型,就像使用内置的全连接层一样使用自定义层 net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))
六、读写文件
1、加载和保存张量
#加载 x = torch.arange(4) torch.save(x, 'x-file') #下载 x2 = torch.load('x-file')
2、加载和保存张量列表
y = torch.zeros(4) torch.save([x, y],'x-files') x2, y2 = torch.load('x-files') (x2, y2)
3、写入或读取从字符串映射到张量的字典
mydict = {'x': x, 'y': y} torch.save(mydict, 'mydict') mydict2 = torch.load('mydict') mydict2
4、加载和保存模型参数
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()