(一) 神经网络模型搭建官方文档
每一层基本都有权重和偏置,可以仔细看官方文档。
pytorch 官网的库:torch.nn — PyTorch 2.5 documentation

- Containers库:用来搭建神经网络框架(包含所有的神经网络的框架);
- 特征提取: 
  - Convolution Layers:用来搭建卷积层;
- Pooling layers:用来搭建池化层;
- Padding Layers:用来搭建填充层;
 
- 分类: 
  - Linear Layers:用来搭建全连接层。
 
(二) 神经网络模型模版(Containers库中的nn.Module)
在写代码的过程中,通常会把神经网络定义成一个类(class),其模版就如下所示:
# 我们的模型类应该继承自nn.Module,这是所有神经网络模块的基类。
# 每个模型类中,都必须要定义以下两个
class LinearModel(torch.nn.Module): # 其中nn是神经网络neural network的缩写
    def __init__(self): # 构造函数,初始化对象时调用的函数,名字也不能变
        super(LinearModel,self).__init__() # 直接写super().__init__()也行
        self.linear = torch.nn.Linear(1,1)
    def forward(self, x): # 前向传播函数,就必须要叫这个名字,因为 nn.Module 类的call方法里调用了名为forward函数
        y_pred = self.linear(x)
        return y_pred
model = LinearModel()
# 其中反向传播的计算,是自动进行的,所有继承自Module的类,都如此。
示例:
import torch
from torch import nn
class testNet(nn.Module):
	def __init__(self):
		super(testNet, self).__init__()
	def forward(self, input):
		output = input + 4
		return output
first_net = testNet()
x = torch.tensor(1.0)
output = first_net(x) # 因为 nn.Module 类的call方法里调用了名为forward函数,所以这里可以直接将实例当做函数使用。
print(output)
------------------------------------------------------------------------------------------------------------------
# 运行结果
tensor(5.)
(三) 神经网络训练套路(四部曲)
其中的损失函数、优化器,以及训练循环体后面会详细讲解
准备数据集 → 设计模型 → 创建损失函数和优化器 → 写训练循环体。
以逻辑回归为例:

| 上一篇 | 下一篇 | 
|---|---|
| 神经网络入门实战(八) | 神经网络入门实战(十) | 



















