pytorch查看模型的梯度和权重和保存模型及其参数

文章介绍了如何在PyTorch中保存和加载模型,包括整个模型结构及参数的保存与加载,以及仅加载模型参数的方法。同时展示了查看模型参数的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:保存模型

保存整个模型 torch.save(model,'net.pth')

保存模型参数 torch.save(model.state_dict(), 'net_params.pth')

import torch

# 保存模型步骤
torch.save(model, 'net.pth')  # 保存整个神经网络的模型结构以及参数
torch.save(model, 'net.pkl')  # 同上
torch.save(model.state_dict(), 'net_params.pth')  # 只保存模型参数
torch.save(model.state_dict(), 'net_params.pkl')  # 同上

# 加载模型步骤
model = torch.load('net.pth')  # 加载整个神经网络的模型结构以及参数
model = torch.load('net.pkl')  # 同上
model.load_state_dict(torch.load('net_params.pth')) # 仅加载参数
model.load_state_dict(torch.load('net_params.pkl')) # 同上

2:参数查看

有网络框架后加载的参数查看
model.parameters(), model.named_parameters()

for parameters in net.parameters():
    print(parameters)
    
for name,parameters in net.named_parameters():
    print(name,':',parameters)
    print(name, ':', parameters.size())

仅仅加载的参数查看,无需建立网络框架

model_dict.items()

import torch

model_dict  = torch.load('Final_LPRNet_model.pth',map_location = 'cpu')
for name, para in model_dict.items():
    print(name,':',para.size())


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值