Pytorch--模型加载

本文详细介绍了PyTorch中模型加载与保存的相关操作,包括使用`load_state_dict()`加载模型参数,利用`nn.DataParallel`进行模型并行化,以及如何保存和加载整个模型状态。同时,还展示了如何只加载特定层的参数,以及设置模型层参数的训练状态。通过实例代码演示了整个流程。
摘要由CSDN通过智能技术生成

一、 Pytorch–模型加载

1、load_state_dict()函数使用

model = VGG()# 实例化自己的模型;
checkpoint = torch.load('checkpoint.pt', map_location='cpu')  # 加载模型文件,pt, pth 文件都可以;
if torch.cuda.device_count() > 1:
    # 如果有多个GPU,将模型并行化,用DataParallel来操作。这个过程会将key值加一个"module. ***"。
    model = nn.DataParallel(model) 
model.load_state_dict(checkpoint) # 接着就可以将模型参数load进模型。

如果有多个GPU,将模型并行化,用DataParallel来操作。
2、state_dict()一个简单的python的字典对象,将每一层与它的对应参数建立映射关系,
是在定义了model或optimizer之后pytorch自动生成的,可以直接调用.常用的保存state_dict的格式是".pt"或’.pth’的文件,即下面命令的 PATH="./***.pt"

torch.save(model.state_dict(), PATH)

注:只有那些参数可以训练的layer才会被保存到模型的state_dict中,如卷积层,线性层等等
3、仅保存学习到的参数,并加载

torch.save(model.state_dict(), PATH)

model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))

for param_tensor in model.state_dict():
    print(param_tensor,'\t',model.state_dict()[param_tensor].size())
    
model.eval()

4、保存整个model的状态,与加载

torch.save(model,PATH)

model = torch.load(PATH)
model.eval()

5、仅加载某一层的训练的到的参数,设置某层某参数的"是否需要训练"(param.requires_grad)

conv1_weight_state = torch.load('./model_state_dict.pt')['conv1.weight']

for param in list(model.pretrained.parameters()):
 param.requires_grad = False

6、全部代码

#-*-coding:utf-8-*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
 
 
 
# define model
class TheModelClass(nn.Module):
    def __init__(self):
        super(TheModelClass,self).__init__()
        self.conv1 = nn.Conv2d(3,6,5)
        self.pool = nn.MaxPool2d(2,2)
        self.conv2 = nn.Conv2d(6,16,5)
        self.fc1 = nn.Linear(16*5*5,120)
        self.fc2 = nn.Linear(120,84)
        self.fc3 = nn.Linear(84,10)
 
    def forward(self,x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1,16*5*5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
 
# initial model
model = TheModelClass()
 
#initialize the optimizer
optimizer = optim.SGD(model.parameters(),lr=0.001,momentum=0.9)
 
# print the model's state_dict
print("model's state_dict:")
for param_tensor in model.state_dict():
    print(param_tensor,'\t',model.state_dict()[param_tensor].size())
 
print("\noptimizer's state_dict")
for var_name in optimizer.state_dict():
    print(var_name,'\t',optimizer.state_dict()[var_name])
 
print("\nprint particular param")
print('\n',model.conv1.weight.size())
print('\n',model.conv1.weight)
 
print("------------------------------------")
torch.save(model.state_dict(),'./model_state_dict.pt')
# model_2 = TheModelClass()
# model_2.load_state_dict(torch.load('./model_state_dict'))
# model.eval()
# print('\n',model_2.conv1.weight)
# print((model_2.conv1.weight == model.conv1.weight).size())
## 仅仅加载某一层的参数
conv1_weight_state = torch.load('./model_state_dict.pt')['conv1.weight']
print(conv1_weight_state==model.conv1.weight)
 
model_2 = TheModelClass()
model_2.load_state_dict(torch.load('./model_state_dict.pt'))
model_2.conv1.requires_grad=False
print(model_2.conv1.requires_grad)
print(model_2.conv1.bias.requires_grad)``

>https://blog.csdn.net/Strive_For_Future/article/details/83240081
PSPNet(Pyramid Scene Parsing Network)是一种用于图像分割的深度学习模型,它在场景解析任务中表现突出,能够处理不同尺度的信息。PyTorch是一个广泛使用的深度学习框架,它提供了构建和训练复杂神经网络的工具。将PyTorch模型转换为ONNX(Open Neural Network Exchange)格式是一种常见做法,旨在实现模型在不同深度学习框架之间的兼容性,从而能够在不同的推理引擎上部署和执行。 要使用`pspnet-pytorch-master`模型进行ONNX推理,你需要遵循以下步骤: 1. **模型准备**:确保你已经安装了PyTorch,并且已经获取了`pspnet-pytorch-master`模型的代码和预训练权重。这通常涉及到克隆GitHub仓库并安装所需的依赖项。 2. **模型转换**:使用PyTorch的ONNX导出功能,将模型转换为ONNX格式。这需要在PyTorch中运行模型并捕获模型的输出,以生成ONNX模型文件。 3. **验证转换**:在转换模型后,你应该验证转换后的ONNX模型是否能够正确地执行推理,与原PyTorch模型的输出保持一致。 4. **ONNX推理**:一旦确认ONNX模型无误,就可以使用支持ONNX的推理引擎(如ONNX Runtime, TensorRT等)来进行高效的推理。 以下是一个简化的代码示例,展示了如何将PyTorch模型导出为ONNX格式: ```python import torch from pspnet import PSPNet # 假设你已经导入了PSPNet类 # 加载预训练的PSPNet模型 model = PSPNet() # 假设这里已经加载了预训练权重 model.eval() # 设置为评估模式 # 创建一个dummy输入,用于模型的前向传播,以便生成ONNX模型 dummy_input = torch.randn(1, 3, 475, 475) # 这里的维度可能需要根据实际模型调整 # 导出模型到ONNX torch.onnx.export(model, dummy_input, "pspnet.onnx", verbose=True, input_names=['input'], output_names=['output']) # 使用ONNX模型进行推理 import onnx import onnxruntime # 加载ONNX模型 onnx_model = onnx.load("pspnet.onnx") onnx.checker.check_model(onnx_model) # 使用ONNX Runtime进行推理 ort_session = onnxruntime.InferenceSession("pspnet.onnx") ort_inputs = {ort_session.get_inputs()[0].name: dummy_input.numpy()} ort_outs = ort_session.run(None, ort_inputs) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值