Pytorch 模型加载

Pytorch加载模型

当在特殊环境下会出现模型无法通过设置pretrained=True的方式来完成自动加载,这时我们需要完成手动加载。我们假设模型设置为:

class Model(nn.Module):
    def __init__(self, num_classes=21):
        super(Model, self).__init__()
        self.backbone = timm.create_model('swin_tiny_patch4_window7_224', pretrained=True)
        self.fc = nn.Linear(1000, num_classes)

    def forward(self, x):
        x = self.backbone(x)
        x = self.fc(x)
        return x

使用timm包下的SwinTransformer作为例子

	model = Model()
    model_dict = model.state_dict()
    print(model_dict.keys())    ## 可以通过.keys()来查看模型结构的state_dict的名称
    resume = True
    if resume:
        print("Resume from checkpoint...")
        checkpoint = torch.load('/root/.cache/torch/hub/checkpoints/swin_tiny_patch4_window7_224.pth')
		# 首先使用torch.load()加载模型的state_dict
		print(checkpoint.key())       #通过.key()查看名称
        model_param = checkpoint['model']
        model_param = {"backbone." + k: v for k, v in model_param.items() if "backbone." + k in model_dict}
		# "backbone." + k 中的"backbone."是根据模型参数和模型结构的state_dict差异决定的
        
        model_dict.update(model_param)
        model.load_state_dict(model_param)       # 固定搭配
        print("====>loaded checkpoint ")
    else:
        print("====>no checkpoint found.")

即可完成模型参数的加载。

同时也可以将上方的代码直接加入 class 中

class Model(nn.Module):
    def __init__(self, num_classes=45):
        super(Model, self).__init__()
        model = timm.create_model('swin_tiny_patch4_window7_224', pretrained=False)
        model_dict = model.state_dict()
        resume = True
        if resume:
            print("Resume from checkpoint...")
            checkpoint = torch.load('/root/.cache/torch/hub/checkpoints/swin_tiny_patch4_window7_224.pth')
            model_param = checkpoint['model']
            model_param = {k: v for k, v in model_param.items() if k in model_dict}  
            # 在此处就不需要添加多余的前缀
            model_dict.update(model_param)
            model.load_state_dict(model_param)
            print("====>loaded checkpoint ")
        else:
            print("====>no checkpoint found.")

        self.backbone = model
        self.fc = nn.Linear(1000, num_classes)

    def forward(self, x):
        x = self.backbone(x)
        x = self.fc(x)
        return x

当前还存在一个问题,就是如果输入的模型numworks不设置为1000的话,就会导致在加载模型的最后一层报错
在这里插入图片描述
使用model.load_state_dict(model_param, False)也无法完成加载。

该问题尚未解决,期待解决方案!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当你构建好PyTorch模型并训练完成后,需要把模型保存下来以备后续使用。这时你需要学会如何加载这个模型,以下是PyTorch模型加载方法的汇总。 ## 1. 加载整个模型 ```python import torch # 加载模型 model = torch.load('model.pth') # 使用模型进行预测 output = model(input) ``` 这个方法可以轻松地加载整个模型,包括模型的结构和参数。需要注意的是,如果你的模型是在另一个设备上训练的(如GPU),则需要在加载时指定设备。 ```python # 加载模型到GPU device = torch.device('cuda') model = torch.load('model.pth', map_location=device) ``` ## 2. 加载模型参数 如果你只需要加载模型参数,而不是整个模型,可以使用以下方法: ```python import torch from model import Model # 创建模型 model = Model() # 加载模型参数 model.load_state_dict(torch.load('model.pth')) # 使用模型进行预测 output = model(input) ``` 需要注意的是,这个方法只能加载模型参数,而不包括模型结构。因此,你需要先创建一个新的模型实例,并确保它的结构与你保存的模型一致。 ## 3. 加载部分模型参数 有时候你只需要加载模型的部分参数,而不是全部参数。这时你可以使用以下方法: ```python import torch from model import Model # 创建模型 model = Model() # 加载部分模型参数 state_dict = torch.load('model.pth') new_state_dict = {} for k, v in state_dict.items(): if k.startswith('layer1'): # 加载 layer1 的参数 new_state_dict[k] = v model.load_state_dict(new_state_dict, strict=False) # 使用模型进行预测 output = model(input) ``` 这个方法可以根据需要选择加载模型的部分参数,而不用加载全部参数。 ## 4. 加载其他框架的模型 如果你需要加载其他深度学习框架(如TensorFlow)训练的模型,可以使用以下方法: ```python import torch import tensorflow as tf # 加载 TensorFlow 模型 tf_model = tf.keras.models.load_model('model.h5') # 将 TensorFlow 模型转换为 PyTorch 模型 input_tensor = torch.randn(1, 3, 224, 224) tf_output = tf_model(input_tensor.numpy()) pytorch_model = torch.nn.Sequential( # ... 构建与 TensorFlow 模型相同的结构 ) pytorch_model.load_state_dict(torch.load('model.pth')) # 使用 PyTorch 模型进行预测 pytorch_output = pytorch_model(input_tensor) ``` 这个方法先将 TensorFlow 模型加载到内存中,然后将其转换为 PyTorch 模型。需要注意的是,转换过程可能会涉及到一些细节问题,因此可能需要进行一些额外的调整。 ## 总结 PyTorch模型加载方法有很多,具体要根据实际情况选择。在使用时,需要注意模型结构和参数的一致性,以及指定正确的设备(如GPU)。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值