深度学习笔记

本文介绍了PyTorch中层和块的概念,包括nn.Sequential的使用,自定义块的定义,以及参数的访问、初始化和共享。此外,还讲解了如何保存和加载模型的参数及张量数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、层和块

        1. (block)可以描述单个层、由多个层组成的组件或整个模型本身。

        块由 类(class) 表示。 它的任何子类都必须定义一个将其输入转换为输出的前向传播函数, 并且必须存储任何必需的参数。 有些块不需要任何参数。 

        下面的代码生成一个网络,其中包含一个具有256个隐藏单元和ReLU激活函数的全连接隐藏层, 然后是一个具有10个隐藏单元且不带激活函数的全连接输出层。

import torch                                         
from torch import nn                                 
from torch.nn import functional as F                 #引入神经网络中的函数

#定义神经网络模型,其中包含一个隐藏层,共有256个隐单元
net = nn.Sequential(nn.Linear(20,256), nn.ReLU(), nn.Linear(256,10))

#生成均匀分布的数值,其中torch.randn()生成的是标准正态分布
X = torch.rand(2, 20)

net(X)                                                #输出神经网络预测的值

输出:

tensor([[-0.1779,  0.0444,  0.0364,  0.0319, -0.3020,  0.1947, -0.0332,  0.0709,
          0.1321, -0.0129],
        [-0.1870, -0.0542,  0.1710, -0.0071, -0.2928,  0.2842,  0.0484,  0.0739,
         -0.0333, -0.0661]], grad_fn=<AddmmBackward0>)

        在这个例子中, nn.Sequential定义了一种特殊的Module, 在PyTorch中表示一个块的类, 它维护了一个由Module组成的有序列表。 前向传播函数非常简单: 它将列表中的每个块连接在一起,将每个块的输出作为下一个块的输入。

1、自定义块

        .每个块必须提供的基本功能:

      

  1. 将输入数据作为其前向传播函数的参数。

  2. 通过前向传播函数来生成输出。

  3. 计算其输出关于输入的梯度,可通过其反向传播函数进行访问。

  4. 存储和访问前向传播计算所需的参数。

  5. 根据需要初始化模型参数。

         在下面的代码片段中, 编写一个块。 它包含一个多层感知机,其具有256个隐藏单元的隐藏层和一个10维输出层。下面的MLP类继承了表示块的类。 我们的实现只需要提供我们自己的构造函数和前向传播函数。

class MLP(nn.Module):
    # 两个全连接的层
    def __init__(self):
        # 调用MLP的父类Module的构造函数来执行必要的初始化
        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)))

      首先由前向传播函数,它以X作为输入, 计算带有激活函数的隐藏表示,并输出其未规范化的输出值。 在这个MLP实现中,两个层都是实例变量。 

X = torch.rand(2, 20)
# 实例化类
net = MLP()
net(X)

输出:

tensor([[ 0.0605,  0.1928,  0.0543,  0.0146, -0.2271, -0.0047,  0.0372,  0.2795,
         -0.1837,  0.0817],
        [ 0.0925,  0.2875, -0.0036,  0.0543, -0.2413,  0.1087, -0.1652,  0.2277,
         -0.1704,  0.1051]], grad_fn=<AddmmBackward0>)

2、顺序块

     由nn.Sequential()可知,使用来把各个层串联起来,按顺序执行。为了构建我们自己的简化的MySequential, 我们只需要定义两个关键函数

  1. 一种将块逐个追加到列表中的函数;

  2. 一种前向传播函数,用于将输入按追加块的顺序传递给块组成的“链条”。

 下面的MySequential类提供了与默认Sequential类相同的功能

class MySequential(nn.Module):
    def __init__(self, *args):
        super().__init__()
        for idx, module in enumerate(args):
            # 变量_modules中。_module的类型是OrderedDict
            self._modules[str(idx)] = module

    def forward(self, X):
        # OrderedDict保证了按照成员添加的顺序遍历它们
        for block in self._modules.values():
            X = block(X)
        return X

  _init__函数将每个模块逐个添加到有序字典_modules中。

      当MySequential的前向传播函数被调用时, 每个添加的块都按照它们被添加的顺序执行。 现在可以使用我们的MySequential类重新实现多层感知机

net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X)

输出: 

tensor([[ 0.2218,  0.0042,  0.0106, -0.0558, -0.0460, -0.0934,  0.0432, -0.3199,
         -0.0757, -0.1888],
        [ 0.2224,  0.0671, -0.1113, -0.0928, -0.2197, -0.0530,  0.1175, -0.3031,
         -0.0872, -0.2313]], grad_fn=<AddmmBackward0>)

3、前向传播函数中执行代码

        计算函数f(X,W) = c * W^T * X的层, 其中X是输入, W是参数, c是某个在优化过程中没有更新的指定常量

import torch
from torch import nn
from torch.nn import functional as F

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        # 不计算梯度的随机权重参数,其值不改变。
        self.weight = torch.rand((20, 20), requires_grad=False)
        self.linear = nn.Linear(20, 20)

    def forward(self, X):
        # 调用全连接层
        X = self.linear(X)
        # relu激活函数
        X = F.relu(torch.mm(X, self.rand_weight) + 1)
        # 调用全连接层
        X = self.linear(X)
        # 循环:(L1范数)/2 <1 情况下停止
        while X.abs().sum() > 1:
            X /= 2
        return X.sum()

net = MLP()
net(x)

输出:

tensor(0.1862, grad_fn=<SumBackward0>)

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))

X = torch.rand(2, 20)
nest = nn.Sequential(NestMLP(), nn.Linear(16, 20))
nest(X)

输出:

tensor([[-0.2697, -0.0260, -0.0634,  0.1692,  0.2619, -0.1160, -0.0063, -0.1191,
          0.0698,  0.1779,  0.1207,  0.0356, -0.0878, -0.0384,  0.2148, -0.1182,
         -0.0815,  0.0614, -0.3284,  0.2867],
        [-0.2710, -0.0290, -0.0780,  0.1662,  0.2568, -0.1076,  0.0215, -0.1157,
          0.0252,  0.1827,  0.1397,  0.0253, -0.0975, -0.0166,  0.1903, -0.1285,
         -0.0818,  0.0637, -0.3168,  0.2923]], grad_fn=<AddmmBackward0>)

5. 小结

     一个块可以由许多层组成;一个块可以由许多块组成。

    块可以包含代码。

    块负责大量的内部处理,包括参数初始化和反向传播。

    层和块的顺序连接由Sequential块处理。

二、参数

        内容:

              1. 访问参数,用于调试、诊断和可视化;

              2. 参数初始化;

              3. 在不同模型组件间共享参数

  1、参数访问

           state_dict是Python的字典对象,可用于保存模型参数,超参数以及优化器(torch.optim)的状态信息。

import torch
from torch import nn

# 多层感知机
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
X = torch.rand(size=(2, 4))
net(X)

print(net[2].state_dict())

输出:

OrderedDict([('weight', tensor([[-0.1755,  0.1619,  0.3391,  0.1680,  0.3493, -0.3377,  0.1417,  0.1347]])), ('bias', tensor([0.2775]))])

  2、目标参数

        查看偏置,权重

print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)
# 访问权重也是如此
# print(type(net[2].weight))
# print(net[2].weight)
# print(net[2].weight.data)

输出:

<class 'torch.nn.parameter.Parameter'>
Parameter containing:
tensor([-0.0101], requires_grad=True)
tensor([-0.0101])

  3、一次性访问所有参数

        model.named_parameters()方法查看神经网络的参数信息。

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()['0.bias'].data

输出:

tensor([-0.4597,  0.1671,  0.3078, -0.3060,  0.2651,  0.3001,  0.2994,  0.3115])

  4、嵌套块参数

      1.  首先定义一个生成块的函数(可以说是“块工厂”),然后将这些块组合到更大的块中。

import torch
from torch import nn

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(2):
        # 嵌套
        net.add_module(f'block {i}', block1())
    return net

X = torch.rand(2, 4)
block_net = nn.Sequential(block2(), nn.Linear(4, 1))
block_net(X)

        2.查看嵌套结构:

print(block_net)

输出: 

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()
    )
  )
  (1): Linear(in_features=4, out_features=1, bias=True)
)

        3. 访问第一个主要的块中、第二个子块的第一层的偏置项

block_net[0][1][0].bias.data

输出:

block_net[0][1][0].bias.data

5、参数初始化

        1. 调用内置的初始化器

net = nn.Sequential(nn.Linear(2, 4))
X = torch.rand(4, 2)
def init_normal(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, mean=0, std=0.01)
        nn.init.zeros_(m.bias)
net.apply(init_normal)
net[0].weight.data[0], net[0].bias.data[0]

输出:

(tensor([ 0.0159, -0.0039]), tensor(0.))

       2.  nn.init.constant_(m.weight, 1)将所有参数初始化为给定的常数,比如初始化为1

net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
X = torch.rand(2, 4)

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.))
      3. nn.init.xavier_uniform_(tensor, gain=1) 均匀分布 ~ U(−a,a)
X = torch.rand(2, 4)
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))

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_42)
net[2].apply(init_xavier)
print(net[0].weight.data[0])
print(net[2].weight.data)

输出:

tensor([42., 42., 42., 42.])
tensor([[-0.4837,  0.7816,  0.4588,  0.6518,  0.5133,  0.4080,  0.8143, -0.1088]])

6. 参数绑定

        1. 在多个层间共享参数: 我们可以定义多个层,然后使用它的参数来设置另一个层的参数

# 定义共享全连接层,以便可以引用它的参数
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])

    

三、自定义层

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()

2、 带参数的层

        1. 该层需要输入参数:in_unitsunits,分别表示输入数和输出数

class MyLinear(nn.Module):
    def __init__(self, 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
        return F.relu(linear)

# 实例化MyLinear类
linear = MyLinear(5, 3)
linear.weight

        访问其模型参数:

Parameter containing:
tensor([[-0.8684,  1.1125, -1.3112],
        [ 2.0380, -1.2791, -0.9271],
        [ 1.7444,  1.2732,  0.4618],
        [ 1.8079,  1.1563,  0.5868],
        [-1.2203, -0.5723, -1.4701]], requires_grad=True)

        2.  使用自定义层构建模型,就像使用内置的全连接层一样使用自定义层

net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))
X = torch.rand(2, 64)
net(X)

输出:

tensor([[0.],
        [0.]])

3.、小结

        1. 我们可以通过基本层类设计自定义层

        2. 在自定义层定义完成后,我们可以调用该自定义层

        3. 层可以有局部参数,这些参数可以通过内置函数创建

四、读写文件

  1、 加载和保存张量

        1. 对于单个张量,我们可以直接调用loadsave函数分别读写它们

            torch.save(x, 'path')     torch.load('path')

import torch
from torch import nn
from torch.nn import functional as F

x = torch.arange(4)
# 存储
torch.save(x, 'x-file')

# 加载
Y = torch.load('x-file')

          2.  存储一个张量列表,然后把它们读回内存

y = torch.ones(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')

         3.  写入或读取从字符串映射到张量的字典

mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')

2、 加载和保存模型参数

        1. 将模型的参数以字典的形式存储在一个叫做“mlp.params”的文件中。

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)

torch.save(net.state_dict(), 'mlp.params')

        2. 加载模型参数:为了恢复模型,我们实例化了原始多层感知机模型的一个备份

load_state_dict()

mlp1 = MLP()
mlp1.load_state_dict(torch.load('mlp.params'))

        3. 加载后,  两个实例具有相同的模型参数

Y_clone = mlp1(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]])

3. 小结

  1. saveload函数可用于张量对象的文件读写

      2. 我们可以通过参数字典保存和加载网络的全部参数

      3. 保存架构必须在代码中完成,而不是在参数中完成

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值