You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch自定义模型中列表存储的层无法被parameters()识别如何解决

问题原因

PyTorch的nn.Module只会自动注册两类子模块的参数:

  • 直接赋值为类属性的子模块(就是你写self.layer1 = nn.Linear(...)的情况)
  • 存放在PyTorch内置的模块容器(nn.ModuleList、nn.Sequential、nn.ModuleDict等)中的子模块

你用普通Python列表存放层再赋值给self.layers,PyTorch不会把列表内的层识别为需要注册的子模块,自然不会出现在parameters()返回的参数列表里。

解决方案

方案1:用nn.ModuleList替换普通列表

把你原来的普通list换成nn.ModuleList即可,修改后的代码如下:

import torch.nn as nn

class Mnist_Net(nn.Module):
    def __init__(self, input_dim, output_dim, hidden_layers=2, neurons=128):
        super().__init__()
        layers = []
        # 这里顺便修正原循环的逻辑问题,避免层重复/索引错误
        layers.append(nn.Linear(input_dim, neurons))
        for _ in range(hidden_layers - 1):
            layers.append(nn.Linear(neurons, neurons))
        layers.append(nn.Linear(neurons, output_dim))
        # 用nn.ModuleList包裹层列表,完成自动注册
        self.layers = nn.ModuleList(layers)
    
    def forward(self, x):
        # 遍历ModuleList执行前向传播
        for layer in self.layers[:-1]:
            x = nn.ReLU()(layer(x))
        x = self.layers[-1](x)
        return x

此时再打印model.parameters()就可以看到所有层的参数了。

方案2:用nn.Sequential封装(更适合顺序执行的网络)

如果你的网络层是按顺序依次执行的,用nn.Sequential更简便,不需要自己写遍历前向的逻辑:

import torch.nn as nn

class Mnist_Net(nn.Module):
    def __init__(self, input_dim, output_dim, hidden_layers=2, neurons=128):
        super().__init__()
        layers = []
        layers.append(nn.Linear(input_dim, neurons))
        layers.append(nn.ReLU())
        for _ in range(hidden_layers - 1):
            layers.append(nn.Linear(neurons, neurons))
            layers.append(nn.ReLU())
        layers.append(nn.Linear(neurons, output_dim))
        # 用Sequential封装,直接调用即可完成前向
        self.layers = nn.Sequential(*layers)
    
    def forward(self, x):
        return self.layers(x)

内容的提问来源于stack exchange,提问作者Newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:36:00