一、模型參數(shù)的保存和加載
-
torch.save(module.state_dict(), path)
:使用module.state_dict()
函數(shù)獲取各層已經(jīng)訓(xùn)練好的參數(shù)和緩沖區(qū),然后將參數(shù)和緩沖區(qū)保存到path
所指定的文件存放路徑(常用文件格式為.pt
、.pth
或.pkl
)。 -
torch.nn.Module.load_state_dict(state_dict)
:從state_dict
中加載參數(shù)和緩沖區(qū)到Module
及其子類中 。 -
torch.nn.Module.state_dict()
函數(shù)返回python
中的一個(gè)OrderedDict
類型字典對(duì)象,該對(duì)象將每一層與它的對(duì)應(yīng)參數(shù)和緩沖區(qū)建立映射關(guān)系,字典的鍵值是參數(shù)或緩沖區(qū)的名稱。只有那些參數(shù)可以訓(xùn)練的層才會(huì)被保存到OrderedDict
中,例如:卷積層、線性層等。 -
Python
中的字典類以“鍵:值
”方式存取數(shù)據(jù),OrderedDict
是它的一個(gè)子類,實(shí)現(xiàn)了對(duì)字典對(duì)象中元素的排序(OrderedDict
根據(jù)放入元素的先后順序進(jìn)行排序)。由于進(jìn)行了排序,所以順序不同的兩個(gè)OrderedDict
字典對(duì)象會(huì)被當(dāng)做是兩個(gè)不同的對(duì)象。 - 示例:
import torch import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 2, 3) self.pool1 = nn.MaxPool2d(2, 2) def forward(self, x): x = self.conv1(x) x = self.pool1(x) return x # 初始化網(wǎng)絡(luò) net = Net() net.conv1.weight[0].detach().fill_(1) net.conv1.weight[1].detach().fill_(2) net.conv1.bias.data.detach().zero_() # 獲取state_dict state_dict = net.state_dict() # 字典的遍歷默認(rèn)是遍歷key,所以param_tensor實(shí)際上是鍵值 for param_tensor in state_dict: print(param_tensor,": ",state_dict[param_tensor]) # 保存模型參數(shù) torch.save(state_dict,"net_params.pth") # 通過加載state_dict獲取模型參數(shù) net.load_state_dict(state_dict)
輸出:
二、完整模型的保存和加載
-
torch.save(module, path)
:將訓(xùn)練完的整個(gè)網(wǎng)絡(luò)模型module
保存到path
所指定的文件存放路徑(常用文件格式為.pt
或.pth
)。 -
torch.load(path)
:加載保存到path
中的整個(gè)神經(jīng)網(wǎng)絡(luò)模型。 - 示例:
import torch import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 2, 3) self.pool1 = nn.MaxPool2d(2, 2) def forward(self, x): x = self.conv1(x) x = self.pool1(x) return x # 初始化網(wǎng)絡(luò) net = Net() net.conv1.weight[0].detach().fill_(1) net.conv1.weight[1].detach().fill_(2) net.conv1.bias.data.detach().zero_() # 保存整個(gè)網(wǎng)絡(luò) torch.save(net,"net.pth") # 加載網(wǎng)絡(luò) net = torch.load("net.pth")
到此這篇關(guān)于PyTorch深度學(xué)習(xí)模型的保存和加載流程詳解的文章就介紹到這了,更多相關(guān)PyTorch 模型的保存 內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/m0_52650517/article/details/120836999