在PyTorch中搭建神经网络 📅 发布时间:2026/9/8 15:25:09 👁 浏览次数: 模板骨架所有自定义网络都遵循这套模板import torch from torch import nn # 1.定义网络类继承nn.Module class MyNet(nn.Module): def __init__(self): super().__init__() # 必须调用父类构造函数 # --------在这里定义所有网络层/容器(Linear、ReLU、Sequential等)-------- # self.xxx 层实例 def forward(self, x): # --------在这里写数据流动逻辑输入x经过各层计算返回输出-------- # x self.xxx(x) return x # 2.测试网络 if __name__ __main__: # 构造模拟输入数据 input_data torch.randn(形状) net MyNet() # 实例化网络 out net(input_data) # 前向传播自动调用forward print(out.shape)搭建神经网络示例from torch import nn import torch class FullyConnectedNet(nn.Module): def __init__(self): super().__init__() self.layer nn.Sequential( nn.Flatten(), # [batch, 1, 28, 28] - [batch, 784] nn.Linear(28 * 28, 512), # 784 个像素点映射到 512 个隐藏特征 nn.ReLU(), # 增加非线性表达能力 nn.Linear(512, 256), # 继续提取更紧凑的隐藏特征 nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 10), # 模型输出的原始分数(分数越高说明模型当前越偏向哪个候选项) ) def forward(self, x): return self.layer(x) if __name__ __main__: data torch.randn(1,1,28,28) net FullyConnectedNet() output net(data) print(output)from torch import nnnn是什么from torch import nntorch是顶层大模块nn是 torch 下面的一个子模块module全称torch.nn专门用来搭建神经网络。等价写法import torch nn torch.nn # 完全一样torch.nn 里面装了什么里面全是神经网络相关的类、工具网络层类nn.Linear、nn.Conv2d、nn.Flatten、nn.ReLU、nn.Sequential模型基类nn.Module—— 所有网络 / 层都继承它损失函数类nn.CrossEntropyLoss、nn.MSELoss容器nn.Sequential、nn.ModuleList、nn.ModuleDict归一化、dropout、embedding等等语法拆解from torch import nn # 从 torch 包中导入 nn 子模块当前文件就可以直接写 nn.xxx不用写 torch.nn.xxxnn模块对象不是类不是函数。nn.Sequential访问 nn 模块内部的Sequential类nn.Sequential(...)实例化这个类得到一个网络层对象层级关系梳理torch (顶层包) └── nn 子模块(torch.nn) ├── nn.Module 【基类】 ├── nn.Sequential 【类继承Module】 ├── nn.Linear 【全连接层类】 ├── nn.ReLU 【激活类】 └── nn.CrossEntropyLoss 损失类重点 所有层nn.Linear()、nn.ReLU()、nn.Sequential()都是实例化类返回的实例全部继承自nn.Module。 只有继承nn.Module的对象放到模型里面参数才会被自动管理net.parameters()、cuda、保存加载模型。容易混淆对比代码是什么torch最顶层包nntorch.nn神经网络子模块nn.Module类所有网络组件的父类nn.Sequential类Module 的子类nn.Sequential(...)实例化得到 Module 实例对象self.layer nn.Sequential(...)self.layer是模型的属性存这个 Module 实例小坑提醒self.layer nn.Sequential # ❗错误没有括号只是把类本身赋值没有创建对象 self.layer nn.Sequential() # ✅加括号实例化生成对象