AI知识分享AI知识分享
✿导航
  • 人工智能
  • 神经网络
  • 机器学习
  • 深度学习
  • 强化学习
  • 自然语言处理
  • 计算机视觉
  • 大模型基础
  • 动手学深度学习
  • 理论理解
  • 工程实践
  • 应用开发
  • AI For Everyone
  • AIGC_2024大会
  • AIGC_2025大会
  • Transformer
  • Pytorch
  • HuggingFace
  • 蒸馏
  • RAG
  • 目标检测
  • MCP
  • 概念
  • 意图识别
  • 工具
✿导航
  • 人工智能
  • 神经网络
  • 机器学习
  • 深度学习
  • 强化学习
  • 自然语言处理
  • 计算机视觉
  • 大模型基础
  • 动手学深度学习
  • 理论理解
  • 工程实践
  • 应用开发
  • AI For Everyone
  • AIGC_2024大会
  • AIGC_2025大会
  • Transformer
  • Pytorch
  • HuggingFace
  • 蒸馏
  • RAG
  • 目标检测
  • MCP
  • 概念
  • 意图识别
  • 工具
  • 大模型基础

    • 语言模型基础

      • 概述
      • 基于统计方法的语言模型
      • 基于神经网络的语言模型
      • 语言模型的采样方法
      • 语言模型的评测
    • 大语言模型架构

      • 概述
      • 主流模型架构
      • Encoder-only
      • Encoder-Decoder
      • Decoder-only
      • 非Transformer 架构
    • Prompt工程

      • 工程简介
      • 上下文学习
      • 思维链
      • 技巧
    • 参数高效微调

      • 概述
      • 参数附加方法
      • 参数选择方法
      • 低秩适配方法
      • 实践与应用
    • 模型编辑

      • 简介
      • 方法
      • 附加参数法
      • 定位编辑法
    • RAG

      • 基础
      • 架构
      • 知识检索
      • 生成增强
  • 动手学深度学习

    • 深度学习基础

      • 引言
      • 数据操作
      • 数据预处理
      • 数学知识(线代、矩阵计算、求导)
      • 线性回归
      • 基础优化方法
      • Softmax回归
      • 感知机
      • 模型选择
      • 过拟合和欠拟合
      • 环境和分布偏移
      • 权重衰减
      • Dropout
      • 数值稳定性
    • 卷积神经网络

      • 模型基本操作
      • 从全连接层到卷积
      • 填充和步长
      • 多个输入和输出通道
      • 池化层
      • LeNet
      • AlexNet
      • VGG
      • NiN网络
      • GoogleNet
      • 批量归一化
      • ResNet
    • 计算机视觉

      • 图像增广
      • 微调
      • 目标检测
      • 锚框
      • 区域卷积神经网络
      • 单发多框检测
      • 一次看完
      • 语义分割
      • 转置卷积
      • 全连接卷积神经网络
      • 样式迁移
    • 循环神经网络

      • 序列模型
      • 语言模型
      • 循环神经网络
      • 序列到序列学习
      • 搜索策略
    • 注意力机制

      • 优化算法

模型基本操作

模型构造

详情
<!-- #include-env-start: D:/code/klc/test/share4ai/docs/book/dive_into_on_dl/cnn/basic -->
```python
# 解决 jupyter notebook Kernel Restarting内核崩溃
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 多层感知机(MLP):通过堆叠多个“全连接层 + 非线性激活函数”,让网络能逐步提取更高层次的抽象特征。
import torch
from torch import nn
from torch.nn import functional as F

net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)) # 标准 MLP

X = torch.rand(2, 20)
net(X)
tensor([[ 0.1178, -0.0854,  0.0831, -0.1375, -0.4059,  0.1283, -0.0432, -0.1464,
         -0.0142, -0.0036],
        [ 0.0686, -0.0613, -0.0517, -0.1408, -0.2585,  0.0608, -0.1787, -0.0973,
          0.0242,  0.0182]], grad_fn=<AddmmBackward0>)
# 自定义块
class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.out = nn.Linear(256, 10)

    def forward(self, X):
        return self.out(F.relu(self.hidden(X)))
net = MLP()
net(X)
tensor([[-0.1129, -0.0153, -0.0360,  0.3818, -0.0830, -0.0019, -0.1218,  0.1305,
          0.2558,  0.0961],
        [-0.0782, -0.0457, -0.0567,  0.2353, -0.1075,  0.0020, -0.1743,  0.0302,
          0.1166,  0.0955]], grad_fn=<AddmmBackward0>)
# 顺序块
class MySequential(nn.Module):
    def __init__(self, *args):
        super().__init__()
        for block in args:
            self._modules[block] = block

    def forward(self, X):
        for block in self._modules.values():
            X = block(X)
        return X

net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X)
tensor([[-0.0202,  0.0352, -0.1756, -0.1081,  0.2118,  0.0204, -0.0870, -0.0380,
         -0.1469, -0.1610],
        [-0.0717, -0.0195, -0.0532, -0.0087,  0.0455,  0.1199, -0.1019, -0.0271,
         -0.0535, -0.1960]], grad_fn=<AddmmBackward0>)

参数管理

详情
<!-- #include-env-start: D:/code/klc/test/share4ai/docs/book/dive_into_on_dl/cnn/basic -->
```python
# 解决 jupyter notebook Kernel Restarting内核崩溃
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 参数管理
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))
X, net(X)
(tensor([[0.5391, 0.3694, 0.2500, 0.4317],
         [0.6047, 0.1190, 0.1498, 0.5952]]),
 tensor([[-0.2790],
         [-0.2295]], grad_fn=<AddmmBackward0>))
# 参数访问
print(net[2].state_dict())
OrderedDict({'weight': tensor([[ 0.0553,  0.1197, -0.2276,  0.0081,  0.2472, -0.1200, -0.1863,  0.2110]]), 'bias': tensor([-0.3343])})
# 目标参数
print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)
<class 'torch.nn.parameter.Parameter'>
Parameter containing:
tensor([-0.3343], requires_grad=True)
tensor([-0.3343])
net[2].weight.grad == None
True
# 一次性访问所有参数
print(*[(name, param.shape) for name, param in net.named_parameters()])
('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()['2.bias'].data
tensor([-0.3343])
# 从嵌套块收集参数
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(4):
        net.add_module(f'block {i}', block1())
    return net

rgnet = nn.Sequential(block2(), nn.Linear(4, 1))
rgnet(X)
tensor([[-0.0915],
        [-0.0915]], grad_fn=<AddmmBackward0>)
print(rgnet)
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()
    )
    (block 2): 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 3): 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)
)
# 内置初始化
def init_normal(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, mean=0, std=0.01) # 使用正态分布(高斯分布) 初始化权重,均值 mean = 0,标准差 std = 0.01。_ 表示原地操作(in-place),提高效率
        nn.init.zeros_(m.bias)

net.apply(init_normal) # net.apply(fn) 是 nn.Module 的方法,会递归遍历网络中所有子模块,并对每个子模块调用 fn(module)。
net[0].weight.data[0], net[0].bias.data[0]
(tensor([-0.0101, -0.0012,  0.0055,  0.0084]), tensor(0.))
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.))
# 对某些块应用不同的初始化方法
def xavier(m):
    if type(m) == nn.Linear:
        nn.init.xavier_uniform_(m.weight) # 对线性层的权重使用 Xavier(Glorot)均匀初始化。

def init_42(m):
    if type(m) == nn.Linear:
        nn.init.constant_(m.weight, 42) # 常数初始化(固定值 42)

net[0].apply(xavier)
net[2].apply(init_42)
print(net[0].weight.data[0])
print(net[2].weight.data)
tensor([ 0.4430,  0.3981, -0.5062,  0.4422])
tensor([[42., 42., 42., 42., 42., 42., 42., 42.]])
# 自定义初始化
def my_init(m):
    if type(m) == nn.Linear:
        print(
            "Init",
            *[(name, param.shape) for name, param in m.named_parameters()][0])
        nn.init.uniform_(m.weight, -10, 10) # 将权重 m.weight 原地初始化为从 Uniform(-10, 10) 分布中采样的值。
        m.weight.data *= m.weight.data.abs() >= 5 # 将绝对值小于 5 的权重置为 0,保留绝对值 ≥ 5 的权重

net.apply(my_init)
net[0].weight[:2]
Init weight torch.Size([8, 4])
Init weight torch.Size([1, 8])





tensor([[-0.0000,  0.0000, -0.0000,  8.8023],
        [-7.5122, -8.6979,  9.6287,  0.0000]], grad_fn=<SliceBackward0>)
net[0].weight.data[:] += 1
net[0].weight.data[0, 0] = 42
net[0].weight.data[0]
tensor([42.0000,  1.0000,  1.0000,  9.8023])
# 参数绑定
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])

自定义层

详情
<!-- #include-env-start: D:/code/klc/test/share4ai/docs/book/dive_into_on_dl/cnn/basic -->
```python
# 解决 jupyter notebook Kernel Restarting内核崩溃
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 自定义层
# 构造一个没有任何参数的自定义层
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()

layer = CenteredLayer()
layer(torch.FloatTensor([1, 2, 3, 4, 5]))
tensor([-2., -1.,  0.,  1.,  2.])
# 将层作为组件合并到构建更复杂的模型中
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())

Y = net(torch.rand(4, 8))
Y.mean()
tensor(8.3819e-09, grad_fn=<MeanBackward0>)
# 带参数的层
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)

linear = MyLinear(5, 3)
linear.weight
Parameter containing:
tensor([[-3.1123e-01, -6.0521e-01, -3.8352e-01],
        [ 1.7512e-01, -9.4326e-04, -1.1390e+00],
        [-5.1521e-01,  1.3428e+00, -5.8997e-01],
        [-5.0404e-01,  3.2794e-01, -6.3966e-01],
        [ 7.8106e-01,  1.5842e+00,  5.2333e-01]], requires_grad=True)
# 使用自定义层直接执行正向传播计算

读写文件

详情
<!-- #include-env-start: D:/code/klc/test/share4ai/docs/book/dive_into_on_dl/cnn/basic -->
```python
# 解决 jupyter notebook Kernel Restarting内核崩溃
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 读写文件
# 加载和保存张量
import torch
from torch import nn
from torch.nn import functional as F

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

x2 = torch.load('x-file')
x2
tensor([0, 1, 2, 3])
# 存储一个张量列表,然后把它们读回内存
y = torch.zeros(4)
torch.save([x, y], 'x-files')
x2, y2 = torch.load('x-files')
(x2, y2)
(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))
# 写入或读取从字符串映射到张量的字典
mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2
{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}
# 加载和保存模型参数
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)
# 将模型的参数存储为一个叫做“mlp.params”的文件
torch.save(net.state_dict(), 'mlp.params')
# 实例化了原始多层感知机模型的一个备份。 直接读取文件中存储的参数
clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
clone.eval()
MLP(
  (hidden): Linear(in_features=20, out_features=256, bias=True)
  (output): Linear(in_features=256, out_features=10, bias=True)
)
Y_clone = clone(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]])
最近更新: 2026/3/11 20:33
Contributors: klc407073648
Next
从全连接层到卷积