首页 > 其他分享 >PyTorch笔记:如何保存与加载checkpoints

PyTorch笔记:如何保存与加载checkpoints

时间:2022-11-05 20:56:02浏览次数:72  
标签:nn self torch state PyTorch dict checkpoints model 加载

https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_a_general_checkpoint.html

保存和加载checkpoints很有帮助。
为了保存checkpoints,必须将它们放在字典对象里,然后使用torch.save()来序列化字典。一个通用的PyTorch做法时使用.tar拓展名保存checkpoints。
加载时,首先需要初始化模型和优化器,然后使用torch.load()加载
定义

import torch
import torch.nn as nn
import torch.optim as optim

class Net(nn.Module):
    def __init__(self):
        super(Net, 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

net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

保存checkpoints

# Additional information
EPOCH = 5
PATH = "model.pt"
LOSS = 0.4

torch.save({
            'epoch': EPOCH,
            'model_state_dict': net.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
            'loss': LOSS,
            }, PATH)

加载

model = Net()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

checkpoint = torch.load(PATH)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']
loss = checkpoint['loss']

model.eval()
# - or -
model.train()

标签:nn,self,torch,state,PyTorch,dict,checkpoints,model,加载
From: https://www.cnblogs.com/x-ocean/p/16861255.html

相关文章