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)
相关推荐
摇滚侠10 分钟前
Spring Boot3零基础教程,Actuator 导入,笔记82
java·spring boot·笔记
新智元11 分钟前
英伟达,全球首个 5 万亿美元公司诞生!「GPU 帝国」超日本德国 GDP
人工智能·openai
WarPigs23 分钟前
Blender动画笔记
笔记·blender
音视频牛哥25 分钟前
AI智能体从系统智能到生态智能:SmartMediaKit 如何成为智能体时代的视频神经系统
人工智能·计算机视觉·音视频·大牛直播sdk·多智能体协同·rtsp播放器rtmp播放器·视频感知低延迟音视频
档案宝档案管理26 分钟前
零售行业档案管理的痛点与解决方案:档案管理系统显身手
大数据·数据库·人工智能·档案·零售·档案管理
gustt33 分钟前
让你的 AI 更听话:Prompt 工程的实战秘籍
人工智能·后端·node.js
CyberSoma1 小时前
机器人模仿学习运动基元数学编码方法还有用吗?
人工智能·算法·计算机视觉·机器人
机器之心1 小时前
牛津VGG、港大、上交发布ELIP:超越CLIP等,多模态图片检索的增强视觉语言大模型预训练
人工智能·openai
神经星星1 小时前
【TVM 教程】自定义优化
人工智能·机器学习·编程语言
陈哥聊测试1 小时前
AI Agent是新一轮「技术泡沫」?
人工智能·程序员·产品