最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

pytorch 狀態(tài)字典:state_dict使用詳解

 更新時間:2020年01月17日 17:12:28   作者:wzg2016  
今天小編就為大家分享一篇pytorch 狀態(tài)字典:state_dict使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

pytorch 中的 state_dict 是一個簡單的python的字典對象,將每一層與它的對應參數建立映射關系.(如model的每一層的weights及偏置等等)

(注意,只有那些參數可以訓練的layer才會被保存到模型的state_dict中,如卷積層,線性層等等)

優(yōu)化器對象Optimizer也有一個state_dict,它包含了優(yōu)化器的狀態(tài)以及被使用的超參數(如lr, momentum,weight_decay等)

備注:

1) state_dict是在定義了model或optimizer之后pytorch自動生成的,可以直接調用.常用的保存state_dict的格式是".pt"或'.pth'的文件,即下面命令的 PATH="./***.pt"

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

2) load_state_dict 也是model或optimizer之后pytorch自動具備的函數,可以直接調用

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

注意:model.eval() 的重要性,在2)中最后用到了model.eval(),是因為,只有在執(zhí)行該命令后,"dropout層"及"batch normalization層"才會進入 evalution 模態(tài). 而在"訓練(training)模態(tài)"與"評估(evalution)模態(tài)"下,這兩層有不同的表現形式.

模態(tài)字典(state_dict)的保存(model是一個網絡結構類的對象)

1.1)僅保存學習到的參數,用以下命令

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

1.2)加載model.state_dict,用以下命令

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

備注:model.load_state_dict的操作對象是 一個具體的對象,而不能是文件名

2.1)保存整個model的狀態(tài),用以下命令

torch.save(model,PATH)

2.2)加載整個model的狀態(tài),用以下命令:

   # Model class must be defined somewhere

 model = torch.load(PATH)

 model.eval()

state_dict 是一個python的字典格式,以字典的格式存儲,然后以字典的格式被加載,而且只加載key匹配的項

如何僅加載某一層的訓練的到的參數(某一層的state)

If you want to load parameters from one layer to another, but some keys do not match, simply change the name of the parameter keys in the state_dict that you are loading to match the keys in the model that you are loading into.

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

加載模型參數后,如何設置某層某參數的"是否需要訓練"(param.requires_grad)

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

注意: requires_grad的操作對象是tensor.

疑問:能否直接對某個層直接之用requires_grad呢?例如:model.conv1.requires_grad=False

回答:經測試,不可以.model.conv1 沒有requires_grad屬性.

全部測試代碼:

#-*-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)

以上這篇pytorch 狀態(tài)字典:state_dict使用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • python字符串替換re.sub()方法解析

    python字符串替換re.sub()方法解析

    這篇文章主要介紹了python字符串替換re.sub()方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-09-09
  • Selenium webdriver添加cookie實現過程詳解

    Selenium webdriver添加cookie實現過程詳解

    這篇文章主要介紹了Selenium webdriver添加cookie實現過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-08-08
  • python使用PyCharm進行遠程開發(fā)和調試

    python使用PyCharm進行遠程開發(fā)和調試

    這篇文章主要介紹了python使用PyCharm進行遠程開發(fā)和調試,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • python3中sys.argv的實例用法

    python3中sys.argv的實例用法

    在本篇文章里小編給大家分享的是關于python3中sys.argv的實例用法內容,需要的朋友們可以學習下。
    2020-04-04
  • pandas 對series和dataframe進行排序的實例

    pandas 對series和dataframe進行排序的實例

    今天小編就為大家分享一篇pandas 對series和dataframe進行排序的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • python中not、and和or的優(yōu)先級與詳細用法介紹

    python中not、and和or的優(yōu)先級與詳細用法介紹

    這篇文章主要給大家介紹了python中not、and和or的優(yōu)先級與詳細用法介紹,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11
  • python基礎教程之csv格式文件的寫入與讀取

    python基礎教程之csv格式文件的寫入與讀取

    逗號分隔值(Comma-Separated Values,CSV,也稱為字符分隔值,分隔字符也可以不是逗號),新這篇文章主要給大家介紹了關于python基礎教程之csv格式文件的寫入與讀取的相關資料,需要的朋友可以參考下
    2022-03-03
  • python數據類型強制轉換實例詳解

    python數據類型強制轉換實例詳解

    這篇文章主要介紹了python數據類型強制轉換實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • python讀取圖片顏色值并生成excel像素畫的方法實例

    python讀取圖片顏色值并生成excel像素畫的方法實例

    這篇文章主要給大家介紹了關于python讀取圖片顏色值并生成excel像素畫的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-02-02
  • Python使用pyinstaller打包spec文件的方法詳解

    Python使用pyinstaller打包spec文件的方法詳解

    PyInstaller是一個用于將Python腳本打包成獨立的可執(zhí)行文件的工具,使用PyInstaller您可以將Python應用程序轉換為可執(zhí)行文件,而無需用戶安裝Python解釋器或任何額外的庫,這篇文章主要給大家介紹了關于Python使用pyinstaller打包spec文件的相關資料,需要的朋友可以參考下
    2024-08-08

最新評論

永嘉县| 南通市| 阿克苏市| 图片| 顺义区| 确山县| 雷山县| 崇礼县| 呼和浩特市| 绩溪县| 海丰县| 广河县| 绵阳市| 合阳县| 汉阴县| 长阳| 浪卡子县| 天水市| 黔南| 华宁县| 腾冲县| 高唐县| 衡南县| 扎兰屯市| 通海县| 崇仁县| 法库县| 察雅县| 渑池县| 长丰县| 宁陕县| 泰顺县| 雅江县| 惠州市| 游戏| 洛宁县| 桃园市| 金溪县| 凤庆县| 延边| 公主岭市|