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

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())


 

猜你喜欢

转载自blog.csdn.net/swx595182208/article/details/130162058