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)
相关推荐
Warren2Lynch7 小时前
利用 AI 协作优化软件更新逻辑:构建清晰的 UML 顺序图指南
人工智能·uml
ModelWhale7 小时前
当“AI+制造”遇上商业航天:和鲸助力头部企业,构建火箭研发 AI 中台
人工智能
ATMQuant7 小时前
量化指标解码13:WaveTrend波浪趋势 - 震荡行情的超买超卖捕手
人工智能·ai·金融·区块链·量化交易·vnpy
weixin_509138347 小时前
语义流形探索:大型语言模型中可控涌现路径的实证证据
人工智能·语义空间
优雅的潮叭7 小时前
c++ 学习笔记之 shared_ptr
c++·笔记·学习
soldierluo7 小时前
大模型的召回率
人工智能·机器学习
Gofarlic_oms17 小时前
Windchill用户登录与模块访问失败问题排查与许可证诊断
大数据·运维·网络·数据库·人工智能
童话名剑7 小时前
人脸识别(吴恩达深度学习笔记)
人工智能·深度学习·人脸识别·siamese网络·三元组损失函数
claider7 小时前
Vim User Manual 阅读笔记 usr_08.txt Splitting windows 窗口分割
笔记·编辑器·vim
_YiFei7 小时前
2026年AIGC检测通关攻略:降ai率工具深度测评(含免费降ai率方案)
人工智能·aigc