pytorch笔记:named_parameters

  • named_parameters 是 PyTorch 中一个非常有用的函数,用于访问模型中所有定义的参数及其对应的名称。
  • 它是 torch.nn.Module 类的方法之一,返回一个生成器,生成 (name, parameter) 对,name 是参数的名称,parameter 是对应的参数张量。

1 举例

1.0 创建模型

python 复制代码
import torch
import torch.nn as nn

# 定义一个简单的模型
class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 64, 5)
        self.fc1 = nn.Linear(64 * 4 * 4, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = torch.relu(self.conv1(x))
        x = torch.relu(self.conv2(x))
        x = x.view(-1, 64 * 4 * 4)
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# 实例化模型
model_tst = SimpleModel()

1.1 应用1:打印模型的所有参数及其名称

python 复制代码
for name, param in model_tst.named_parameters():
    print(name, param.shape)

'''
conv1.weight torch.Size([20, 1, 5, 5])
conv1.bias torch.Size([20])
conv2.weight torch.Size([64, 20, 5, 5])
conv2.bias torch.Size([64])
fc1.weight torch.Size([500, 1024])
fc1.bias torch.Size([500])
fc2.weight torch.Size([10, 500])
fc2.bias torch.Size([10])
conv1.weight torch.Size([20, 1, 5, 5])
conv1.bias torch.Size([20])
conv2.weight torch.Size([64, 20, 5, 5])
conv2.bias torch.Size([64])
fc1.weight torch.Size([500, 1024])
fc1.bias torch.Size([500])
fc2.weight torch.Size([10, 500])
fc2.bias torch.Size([10])
'''

1.2 应用2:冻结特定层的参数

假设我们只想训练全连接层,而冻结卷积层的参数:

python 复制代码
for name, param in model_tst.named_parameters():
    if 'conv' in name:
        param.requires_grad = False

1.3 应用3:自定义优化器参数

可以使用 named_parameters 创建自定义的参数组,以便对不同的参数组应用不同的学习率:

python 复制代码
optimizer = torch.optim.SGD([
    {'params': [param for name, param in model_tst.named_parameters() if 'conv' in name], 'lr': 0.01},
    {'params': [param for name, param in model_tst.named_parameters() if 'fc' in name], 'lr': 0.1}
], momentum=0.9)
相关推荐
Y前进四2 分钟前
ICLR 2026 Oral论文阅读 (21篇 对齐、公平、安全、隐私及社会考量)
论文阅读·人工智能
狮子座明仔8 分钟前
当RAG的“压缩包“爆了:如何检测Token溢出?
人工智能·机器学习·语言模型·自然语言处理
Le0v1n8 分钟前
Building Systems with the ChatGPT API(基于 ChatGPT API 构建系统)
人工智能·chatgpt
郝学胜-神的一滴15 分钟前
计算思维:数字时代的超级能力
开发语言·数据结构·c++·人工智能·python·算法
今天你TLE了吗20 分钟前
JVM学习笔记:第四章——虚拟机栈
java·jvm·笔记·后端·学习
tq108621 分钟前
缘木求鱼:追求运行效率是 AI 工具开发的陷阱
人工智能
刘海东刘海东21 分钟前
一条新的人工智能道路
人工智能
AI_567822 分钟前
Sass代码优化:混合宏+占位符提升CSS可维护性
人工智能·sass
KvPiter23 分钟前
一人软件公司 《solopreneur》从0到1
ide·人工智能
shenxianasi24 分钟前
2026年美赛C题思路分享及数学推导
人工智能·机器学习·数学建模