pytorch實(shí)現(xiàn)加載保存查看checkpoint文件
1.保存加載checkpoint文件
# 方式一:保存加載整個(gè)state_dict(推薦) # 保存 torch.save(model.state_dict(), PATH) # 加載 model.load_state_dict(torch.load(PATH)) # 測(cè)試時(shí)不啟用 BatchNormalization 和 Dropout model.eval()
# 方式二:保存加載整個(gè)模型 # 保存 torch.save(model, PATH) # 加載 model = torch.load(PATH) model.eval()
# 方式三:保存用于繼續(xù)訓(xùn)練的checkpoint或者多個(gè)模型
# 保存
torch.save({
? ? ? ? ? ? 'epoch': epoch,
? ? ? ? ? ? 'model_state_dict': model.state_dict(),
? ? ? ? ? ? ...
? ? ? ? ? ? }, PATH)
# 加載
checkpoint = torch.load(PATH)
start_epoch=checkpoint['epoch']
model.load_state_dict(checkpoint['model_state_dict'])
# 測(cè)試時(shí)
model.eval()
# 或者訓(xùn)練時(shí)
model.train()2.跨gpu和cpu
# GPU上保存,CPU上加載
# 保存
torch.save(model.state_dict(), PATH)
# 加載
device = torch.device('cpu')
model.load_state_dict(torch.load(PATH, map_location=device))
# 如果是多gpu保存,需要去除關(guān)鍵字中的module,見第4部分# GPU上保存,GPU上加載
# 保存
torch.save(model.state_dict(), PATH)
# 加載
device = torch.device("cuda")
model.load_state_dict(torch.load(PATH))
model.to(device)# CPU上保存,GPU上加載
# 保存
torch.save(model.state_dict(), PATH)
# 加載
device = torch.device("cuda")
# 選擇希望使用的GPU
model.load_state_dict(torch.load(PATH, map_location="cuda:0")) ?
model.to(device)3.查看checkpoint文件內(nèi)容
# 打印模型的 state_dict
print("Model's state_dict:")
for param_tensor in model.state_dict():
? ? print(param_tensor, "\t", model.state_dict()[param_tensor].size())4.常見問題
多gpu
報(bào)錯(cuò)為KeyError: ‘unexpected key “module.conv1.weight” in state_dict’
原因:當(dāng)使用多gpu時(shí),會(huì)使用torch.nn.DataParallel,所以checkpoint中有module字樣
#解決1:加載時(shí)將module去掉 # 創(chuàng)建一個(gè)不包含`module.`的新OrderedDict from collections import OrderedDict new_state_dict = OrderedDict() for k, v in state_dict.items(): ? ? name = k[7:] # 去掉 `module.` ? ? new_state_dict[name] = v # 加載參數(shù) model.load_state_dict(new_state_dict)
# 解決2:保存checkpoint時(shí)不保存module torch.save(model.module.state_dict(), PATH)
pytorch保存和加載文件的方法,從斷點(diǎn)處繼續(xù)訓(xùn)練
'''本文件用于舉例說明pytorch保存和加載文件的方法'''
import torch as torch
import torchvision as tv
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as transforms
import os
# 參數(shù)聲明
batch_size = 32
epochs = 10
WORKERS = 0 # dataloder線程數(shù)
test_flag = False # 測(cè)試標(biāo)志,True時(shí)加載保存好的模型進(jìn)行測(cè)試
ROOT = '/home/pxt/pytorch/cifar' # MNIST數(shù)據(jù)集保存路徑
log_dir = '/home/pxt/pytorch/logs/cifar_model.pth' # 模型保存路徑
# 加載MNIST數(shù)據(jù)集
transform = tv.transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
train_data = tv.datasets.CIFAR10(root=ROOT, train=True, download=True, transform=transform)
test_data = tv.datasets.CIFAR10(root=ROOT, train=False, download=False, transform=transform)
train_load = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=WORKERS)
test_load = torch.utils.data.DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=WORKERS)
# 構(gòu)造模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 3, padding=1)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
self.conv3 = nn.Conv2d(128, 256, 3, padding=1)
self.conv4 = nn.Conv2d(256, 256, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(256 * 8 * 8, 1024)
self.fc2 = nn.Linear(1024, 256)
self.fc3 = nn.Linear(256, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool(F.relu(self.conv2(x)))
x = F.relu(self.conv3(x))
x = self.pool(F.relu(self.conv4(x)))
x = x.view(-1, x.size()[1] * x.size()[2] * x.size()[3])
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
model = Net().cpu()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 模型訓(xùn)練
def train(model, train_loader, epoch):
model.train()
train_loss = 0
for i, data in enumerate(train_loader, 0):
x, y = data
x = x.cpu()
y = y.cpu()
optimizer.zero_grad()
y_hat = model(x)
loss = criterion(y_hat, y)
loss.backward()
optimizer.step()
train_loss += loss
print('正在進(jìn)行第{}個(gè)epoch中的第{}次循環(huán)'.format(epoch,i))
loss_mean = train_loss / (i + 1)
print('Train Epoch: {}\t Loss: {:.6f}'.format(epoch, loss_mean.item()))
# 模型測(cè)試
def test(model, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for i, data in enumerate(test_loader, 0):
x, y = data
x = x.cpu()
y = y.cpu()
optimizer.zero_grad()
y_hat = model(x)
test_loss += criterion(y_hat, y).item()
pred = y_hat.max(1, keepdim=True)[1]
correct += pred.eq(y.view_as(pred)).sum().item()
test_loss /= (i + 1)
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_data), 100. * correct / len(test_data)))
def main():
# 如果test_flag=True,則加載已保存的模型并進(jìn)行測(cè)試,測(cè)試以后不進(jìn)行此模塊以后的步驟
if test_flag:
# 加載保存的模型直接進(jìn)行測(cè)試機(jī)驗(yàn)證
checkpoint = torch.load(log_dir)
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch']
test(model, test_load)
return
# 如果有保存的模型,則加載模型,并在其基礎(chǔ)上繼續(xù)訓(xùn)練
if os.path.exists(log_dir):
checkpoint = torch.load(log_dir)
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch']
print('加載 epoch {} 成功!'.format(start_epoch))
else:
start_epoch = 0
print('無保存了的模型,將從頭開始訓(xùn)練!')
for epoch in range(start_epoch+1, epochs):
train(model, train_load, epoch)
test(model, test_load)
# 保存模型
state = {'model':model.state_dict(), 'optimizer':optimizer.state_dict(), 'epoch':epoch}
torch.save(state, log_dir)
if __name__ == '__main__':
main()以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python自動(dòng)化測(cè)試框架之unittest使用詳解
unittest是Python自動(dòng)化測(cè)試框架之一,提供了一系列測(cè)試工具和接口,支持單元測(cè)試、功能測(cè)試、集成測(cè)試等多種測(cè)試類型。unittest使用面向?qū)ο蟮乃枷雽?shí)現(xiàn)測(cè)試用例的編寫和管理,可以方便地?cái)U(kuò)展和定制測(cè)試框架,支持多種測(cè)試結(jié)果輸出格式2023-04-04
python機(jī)器學(xué)習(xí)Github已達(dá)8.9Kstars模型解釋器LIME
這篇文章主要為大家介紹了Github已達(dá)8.9Kstars的最佳模型解釋器LIME的使用示例及功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11
Python3多目標(biāo)賦值及共享引用注意事項(xiàng)
這篇文章主要介紹了Python3多目標(biāo)賦值及共享引用注意事項(xiàng),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
python中使用np.delete()的實(shí)例方法
在本篇文章里小編給大家整理的是一篇關(guān)于python中使用np.delete()的實(shí)例方法,對(duì)此有興趣的朋友們可以學(xué)習(xí)參考下。2021-02-02
python函數(shù)也可以是一個(gè)對(duì)象,可以存放在列表中并調(diào)用方式
這篇文章主要介紹了python函數(shù)也可以是一個(gè)對(duì)象,可以存放在列表中并調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
Python中flatten( )函數(shù)及函數(shù)用法詳解
flatten是numpy.ndarray.flatten的一個(gè)函數(shù),即返回一個(gè)一維數(shù)組。這篇文章主要介紹了Python中flatten( )函數(shù),需要的朋友可以參考下2018-11-11

