nn.Module、nn.Sequential和torch.nn.parameter学习笔记

本文详细介绍了PyTorch中构建神经网络的三种关键方法:nn.Module、nn.Sequential及torch.nn.Parameter的具体用法。通过实例演示如何定义自定义层及模型,并进行训练。

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

nn.Module、nn.Sequential和torch.nn.parameter是利用pytorch构建神经网络最重要的三个函数。搞清他们的具体用法是学习pytorch的必经之路。

nn.Module

nn.Module中,自定义层的步骤:
1.自定义一个Module的子类,实现两个基本的函数:
(1)构造 init 函数 (2)层的逻辑运算函数,即正向传播的函数

2.在构造 init 函数中实现层的参数定义。 比如Linear层的权重和偏置,Conv2d层的in_channels, out_channels, kernel_size, stride=1,padding=0, dilation=1, groups=1,bias=True, padding_mode='zeros’这一系列参数;
3.在forward函数里实现前向运算。 一般都是通过torch.nn.functional.***函数来实现,如果该层含有权重,那么权重必须是nn.Parameter类型。
4.补充:一般情况下,我们定义的参数是可以求导的,但是自定义操作如不可导,需要实现backward函数。

例:

# 定义一个 my_layer.py
    import torch
    
    class MyLayer(torch.nn.Module):
        '''
        因为这个层实现的功能是:y=weights*sqrt(x2+bias),所以有两个参数:
        权值矩阵weights
        偏置矩阵bias
        输入 x 的维度是(in_features,)
        输出 y 的维度是(out_features,) 故而
        bias 的维度是(in_fearures,),注意这里为什么是in_features,而不是out_features,注意体会这里和Linear层的区别所在
        weights 的维度是(in_features, out_features)注意这里为什么是(in_features, out_features),而不是(out_features, in_features),注意体会这里和Linear层的区别所在
        '''
        def __init__(self, in_features, out_features, bias=True):
            super(MyLayer, self).__init__()  # 和自定义模型一样,第一句话就是调用父类的构造函数
            self.in_features = in_features
            self.out_features = out_features
            self.weight = torch.nn.Parameter(torch.Tensor(in_features, out_features)) # 由于weights是可以训练的,所以使用Parameter来定义
            if bias:
                self.bias = torch.nn.Parameter(torch.Tensor(in_features))             # 由于bias是可以训练的,所以使用Parameter来定义
            else:
                self.register_parameter('bias', None)
    
        def forward(self, input):
            input_=torch.pow(input,2)+self.bias
            y=torch.matmul(input_,self.weight)
            return y

    自定义模型并训练
    import torch
    from my_layer import MyLayer # 自定义层
    
    
    N, D_in, D_out = 10, 5, 3  # 一共10组样本,输入特征为5,输出特征为3 
    
    # 先定义一个模型
    class MyNet(torch.nn.Module):
        def __init__(self):
            super(MyNet, self).__init__()  # 第一句话,调用父类的构造函数
            self.mylayer1 = MyLayer(D_in,D_out)
    
        def forward(self, x):
            x = self.mylayer1(x)
    
            return x
    
    model = MyNet()
    print(model)
    '''运行结果为:
    MyNet(
    (mylayer1): MyLayer()   # 这就是自己定义的一个层
    )
    '''

    下面开始训练
    # 创建输入、输出数据
    x = torch.randn(N, D_in)  #(10,5)
    y = torch.randn(N, D_out) #(10,3)
    
    
    #定义损失函数
    loss_fn = torch.nn.MSELoss(reduction='sum')
    
    learning_rate = 1e-4
    #构造一个optimizer对象
    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
    
    for t in range(10): # 
        
        # 第一步:数据的前向传播,计算预测值p_pred
        y_pred = model(x)
    
        # 第二步:计算计算预测值p_pred与真实值的误差
        loss = loss_fn(y_pred, y)
        print(f"第 {t} 个epoch, 损失是 {loss.item()}")
    
        # 在反向传播之前,将模型的梯度归零,这
        optimizer.zero_grad()
    
        # 第三步:反向传播误差
        loss.backward()
    
        # 直接通过梯度一步到位,更新完整个网络的训练参数
        optimizer.step()

nn.Sequential

torch.nn.Sequential是一个Sequential容器,模块将按照构造函数中传递的顺序添加到模块中。
与nn.Module相同,nn.Sequential也是用来构建神经网络的,但nn.Sequential不需要像nn.Module那么多过程,可以快速构建神经网络。
使用nn.Module可以根据自己的需求改变传播过程。

        model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )

这个构建网络的方法工作量略有减少,但有特殊需求的网络还是要用nn.Module。

torch.nn.Parameter

torch.nn.Parameter是继承自torch.Tensor的子类,其主要作用是作为nn.Module中的可训练参数使用。它与torch.Tensor的区别就是nn.Parameter会自动被认为是module的可训练参数,即加入到parameter()这个迭代器中去;而module中非nn.Parameter()的普通tensor是不在parameter中的。
nn.Parameter的对象的requires_grad属性的默认值是True,即是可被训练的,这与torh.Tensor对象的默认值相反。
在nn.Module类中,pytorch也是使用nn.Parameter来对每一个module的参数进行初始化的。
例:

class Linear(Module):
    r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        bias: If set to ``False``, the layer will not learn an additive bias.
            Default: ``True``
    Shape:
        - Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
          additional dimensions and :math:`H_{in} = \text{in\_features}`
        - Output: :math:`(N, *, H_{out})` where all but the last dimension
          are the same shape as the input and :math:`H_{out} = \text{out\_features}`.
    Attributes:
        weight: the learnable weights of the module of shape
            :math:`(\text{out\_features}, \text{in\_features})`. The values are
            initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
            :math:`k = \frac{1}{\text{in\_features}}`
        bias:   the learnable bias of the module of shape :math:`(\text{out\_features})`.
                If :attr:`bias` is ``True``, the values are initialized from
                :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
                :math:`k = \frac{1}{\text{in\_features}}`
    Examples::
        >>> m = nn.Linear(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])
    """
    __constants__ = ['in_features', 'out_features']

    def __init__(self, in_features, out_features, bias=True):
        super(Linear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = Parameter(torch.Tensor(out_features, in_features))
        if bias:
            self.bias = Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

    def reset_parameters(self):
        init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)

    def forward(self, input):
        return F.linear(input, self.weight, self.bias)

    def extra_repr(self):
        return 'in_features={}, out_features={}, bias={}'.format(
            self.in_features, self.out_features, self.bias is not None
        )

显然,在__init__(self, in_features, out_features, bias=True)中,下面的代码使用了nn.Parameter()对weights进行了初始化

参考:
https://blog.youkuaiyun.com/qq_27825451/article/details/90705328
https://blog.youkuaiyun.com/qq_28753373/article/details/104179354

<think>嗯,用户想了解PyTorchnn.Sequentialnn.Module的区别及用法。首先,我需要回忆这两个模块的基本概念。nn.ModulePyTorch中所有神经网络模块的基类,用户自定义的模型都需要继承它。而nn.Sequential是一个容器,可以按顺序包装多个层。 然后,区别方面,应该从结构、使用场景、灵活性等方面展开。比如,nn.Sequential适合简单的线性堆叠,而nn.Module更适合复杂的结构,比如分支或者需要自定义forward逻辑的情况。引用中的例子显示,nn.Sequential可以直接按顺序添加层,甚至用OrderedDict来命名,而nn.ModuleList则更适合需要动态操作的模块列表。 接下来,用户可能需要具体的用法示例。比如,用nn.Sequential构建一个简单的CNN,而用nn.Module构建一个带有跳跃连接的模型。这时候需要参考引用中的代码示例,比如引用34中的Sequential用法,以及引用1提到的ModuleListSequential的区别。 还要注意两者的嵌套使用,比如在nn.Module内部使用多个nn.Sequential来组织子模块。同时,性能方面可能没有太大差异,但代码结构会更清晰。 用户可能的应用场景,比如快速搭建简单网络用Sequential,复杂结构用Module。另外,注意事项中提到Sequential需要严格顺序,而Module更灵活,但需要手动定义forward。 最后,生成相关问题的时候,要覆盖两者的比较、适用情况、嵌套使用、选择依据性能影响等方面,帮助用户深入理解。</think>### PyTorch中`nn.Sequential`与`nn.Module`的区别及用法解析 #### 一、核心区别 1. **功能定位** - `nn.Module`是PyTorch中所有神经网络模块的**基类**,所有自定义模型必须继承它,并实现`forward`方法[^1][^3]。 - `nn.Sequential`是`nn.Module`的**子类**,专门用于**顺序堆叠多个模块**的容器,无需手动定义`forward`方法[^4]。 2. **灵活性** - `nn.Module`支持**任意网络结构**(如分支、循环、条件判断),可自由定义参数子模块。 - `nn.Sequential`仅适用于**严格线性堆叠**的结构,例如:$Layer_1 \to Layer_2 \to \dots \to Layer_n$[^4]。 #### 二、典型用法对比 ##### 1. `nn.Sequential`的用法 ```python import torch.nn as nn # 直接堆叠模块(自动命名) model = nn.Sequential( nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10) ) # 使用OrderedDict命名模块 from collections import OrderedDict model = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(784, 256)), ('act', nn.ReLU()), ('fc2', nn.Linear(256, 10)) ])) ``` - **适用场景**:快速搭建简单网络(如全连接网络、线性CNN)[^4]。 ##### 2. `nn.Module`的用法 ```python class CustomModel(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.act = nn.ReLU() self.fc2 = nn.Linear(256, 10) def forward(self, x): x = self.fc1(x) x = self.act(x) return self.fc2(x) ``` - **优势**:支持复杂逻辑(如残差连接、分支结构): ```python class ResidualBlock(nn.Module): def __init__(self): super().__init__() self.fc = nn.Linear(256, 256) self.act = nn.ReLU() def forward(self, x): return x + self.act(self.fc(x)) # 残差连接 ``` #### 三、嵌套使用 1. **`nn.Sequential`嵌套在`nn.Module`中** ```python class ComplexModel(nn.Module): def __init__(self): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, 3), nn.ReLU(), nn.MaxPool2d(2) ) self.classifier = nn.Linear(64*14*14, 10) ``` 2. **`nn.ModuleList`与`nn.Sequential`的配合** - `nn.ModuleList`用于动态管理子模块(如循环中创建层),而`nn.Sequential`直接定义执行顺序: ```python class DynamicModel(nn.Module): def __init__(self, layers): super().__init__() self.layers = nn.ModuleList([nn.Linear(10,10) for _ in range(layers)]) def forward(self, x): for layer in self.layers: x = layer(x) return x ``` #### 四、性能与注意事项 1. **性能差异** - 两者在计算效率上无本质区别,最终都会被编译为计算图。 2. **使用建议** - 优先选择`nn.Sequential`:当网络结构为简单线性堆叠时(代码更简洁)。 - 必须使用`nn.Module`:需要自定义`forward`逻辑或包含复杂结构时。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值