欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pytorch hook 鉤子函數(shù)的用法

 更新時間:2022年03月23日 09:54:42   作者:ctrl A_ctrl C_ctrl V  
這篇文章主要介紹了pytorch hook 鉤子函數(shù)的用法,Hook 是 PyTorch 中一個十分有用的特性,使用后可以不必改變網(wǎng)絡(luò)輸入輸出的結(jié)構(gòu),方便地獲取、改變網(wǎng)絡(luò)中間層變量的值和梯度,下文詳細(xì)介紹需要的小伙伴可以參考一下

鉤子編程(hooking),也稱作“掛鉤”,是計算機(jī)程序設(shè)計術(shù)語,指通過攔截軟件模塊間的函數(shù)調(diào)用、消息傳遞、事件傳遞來修改或擴(kuò)展操作系統(tǒng)、應(yīng)用程序或其他軟件組件的行為的各種技術(shù)。處理被攔截的函數(shù)調(diào)用、事件、消息的代碼,被稱為鉤子(hook)。

Hook 是 PyTorch 中一個十分有用的特性。利用它,我們可以不必改變網(wǎng)絡(luò)輸入輸出的結(jié)構(gòu),方便地獲取、改變網(wǎng)絡(luò)中間層變量的值和梯度。這個功能被廣泛用于可視化神經(jīng)網(wǎng)絡(luò)中間層的 feature、gradient,從而診斷神經(jīng)網(wǎng)絡(luò)中可能出現(xiàn)的問題,分析網(wǎng)絡(luò)有效性。

本文主要用 hook 函數(shù)輸出網(wǎng)絡(luò)執(zhí)行過程中 forward 和 backward 的執(zhí)行順序,以此找到了bug所在。

用法如下:

# 設(shè)置hook func
def hook_func(name, module):
? ? def hook_function(module, inputs, outputs):
? ? ? ? # 請依據(jù)使用場景自定義函數(shù)
? ? ? ? print(name+' inputs', inputs)
? ? ? ? print(name+' outputs', outputs)
? ? return hook_function

# 注冊正反向hook
for name, module in model.named_modules():
? ? module.register_forward_hook(hook_func('[forward]: '+name, module))
? ? module.register_backward_hook(hook_func('[backward]: '+name, module))

如一個簡單的 MNIST 手寫數(shù)字識別的模型結(jié)構(gòu)如下:

class Net(nn.Module):
? ? def __init__(self):
? ? ? ? super(Net, self).__init__()
? ? ? ? self.conv1 = nn.Conv2d(1, 32, 3, 1)
? ? ? ? self.conv2 = nn.Conv2d(32, 64, 3, 1)
? ? ? ? self.dropout1 = nn.Dropout(0.25)
? ? ? ? self.dropout2 = nn.Dropout(0.5)
? ? ? ? self.fc1 = nn.Linear(9216, 128)
? ? ? ? self.fc2 = nn.Linear(128, 10)

? ? def forward(self, x):
? ? ? ? x = self.conv1(x)
? ? ? ? x = F.relu(x)
? ? ? ? x = self.conv2(x)
? ? ? ? x = F.relu(x)
? ? ? ? x = F.max_pool2d(x, 2)
? ? ? ? x = self.dropout1(x)
? ? ? ? x = torch.flatten(x, 1)
? ? ? ? x = self.fc1(x)
? ? ? ? x = F.relu(x)
? ? ? ? x = self.dropout2(x)
? ? ? ? x = self.fc2(x)
? ? ? ? output = F.log_softmax(x, dim=1)
? ? ? ? return output

打印模型:

Net(
? (conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
? (conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
? (dropout1): Dropout(p=0.25, inplace=False)
? (dropout2): Dropout(p=0.5, inplace=False)
? (fc1): Linear(in_features=9216, out_features=128, bias=True)
? (fc2): Linear(in_features=128, out_features=10, bias=True)
)

構(gòu)建hook函數(shù):

# 設(shè)置hook func
def hook_func(name, module):
? ? def hook_function(module, inputs, outputs):
? ? ? ? with open("log_model.txt", 'a+') as f:
? ? ? ? ? ? # 請依據(jù)使用場景自定義函數(shù)
? ? ? ? ? ? f.write(name + ' ? len(inputs): ' + str(len(inputs)) + '\n')
? ? ? ? ? ? f.write(name + ' ? len(outputs): ?' + str(len(outputs)) + '\n')
? ? return hook_function

# 注冊正反向hook
for name, module in model.named_modules():
? ? module.register_forward_hook(hook_func('[forward]: '+name, module))
? ? module.register_backward_hook(hook_func('[backward]: '+name, module))

輸出的前向和反向傳播過程:

[forward]: conv1   len(inputs): 1
[forward]: conv1   len(outputs):  8
[forward]: conv2   len(inputs): 1
[forward]: conv2   len(outputs):  8
[forward]: dropout1   len(inputs): 1
[forward]: dropout1   len(outputs):  8
[forward]: fc1   len(inputs): 1
[forward]: fc1   len(outputs):  8
[forward]: dropout2   len(inputs): 1
[forward]: dropout2   len(outputs):  8
[forward]: fc2   len(inputs): 1
[forward]: fc2   len(outputs):  8
[forward]:    len(inputs): 1
[forward]:    len(outputs):  8
[backward]:    len(inputs): 2
[backward]:    len(outputs):  1
[backward]: fc2   len(inputs): 3
[backward]: fc2   len(outputs):  1
[backward]: dropout2   len(inputs): 1
[backward]: dropout2   len(outputs):  1
[backward]: fc1   len(inputs): 3
[backward]: fc1   len(outputs):  1
[backward]: dropout1   len(inputs): 1
[backward]: dropout1   len(outputs):  1
[backward]: conv2   len(inputs): 2
[backward]: conv2   len(outputs):  1
[backward]: conv1   len(inputs): 2
[backward]: conv1   len(outputs):  1

因?yàn)橹灰P吞幱趖rain狀態(tài),hook_func 就會執(zhí)行,導(dǎo)致不斷輸出 [forward] 和 [backward],所以將輸出內(nèi)容建議寫到文件中,而不是 print

到此這篇關(guān)于pytorch hook 鉤子函數(shù)的用法的文章就介紹到這了,更多相關(guān)pytorch hook 鉤子函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python更換pip源方法過程解析

    Python更換pip源方法過程解析

    這篇文章主要介紹了Python更換pip源方法過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • python統(tǒng)計mysql數(shù)據(jù)量變化并調(diào)用接口告警的示例代碼

    python統(tǒng)計mysql數(shù)據(jù)量變化并調(diào)用接口告警的示例代碼

    這篇文章主要介紹了python統(tǒng)計mysql數(shù)據(jù)量變化并調(diào)用接口告警的示例代碼,幫助大家更好的利用python操作數(shù)據(jù)庫,感興趣的朋友可以了解下
    2020-09-09
  • Python中注釋(多行注釋和單行注釋)的用法實(shí)例

    Python中注釋(多行注釋和單行注釋)的用法實(shí)例

    這篇文章主要給大家介紹了關(guān)于Python中注釋(多行注釋和單行注釋)用法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • VSCode格式化Python文件的方法

    VSCode格式化Python文件的方法

    這篇文章主要介紹了VSCode格式化Python文件的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2023-12-12
  • 安裝pytorch報錯torch.cuda.is_available()=false問題的解決過程

    安裝pytorch報錯torch.cuda.is_available()=false問題的解決過程

    最近想用pytorch,因此裝了pytorch,但是碰到了問題,下面這篇文章主要給大家介紹了關(guān)于安裝pytorch報錯torch.cuda.is_available()=false問題的解決過程,需要的朋友可以參考下
    2022-05-05
  • python爬蟲爬取某網(wǎng)站視頻的示例代碼

    python爬蟲爬取某網(wǎng)站視頻的示例代碼

    這篇文章主要介紹了python爬蟲爬取某網(wǎng)站視頻的示例代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-02-02
  • Python3中對range()逆序的解釋

    Python3中對range()逆序的解釋

    這篇文章主要介紹了Python3中對range()逆序的解釋,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • Python with用法:自動關(guān)閉文件進(jìn)程

    Python with用法:自動關(guān)閉文件進(jìn)程

    這篇文章主要介紹了Python with用法:自動關(guān)閉文件進(jìn)程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • 分析python垃圾回收機(jī)制原理

    分析python垃圾回收機(jī)制原理

    這篇文章主要介紹了python垃圾回收機(jī)制原理,python采用的是引用計數(shù)機(jī)制為主,標(biāo)記-清除和分代收集兩種機(jī)制為輔的策略,有需要的的朋友可以借鑒參考想
    2021-09-09
  • 徹底搞懂 python 中文亂碼問題(深入分析)

    徹底搞懂 python 中文亂碼問題(深入分析)

    現(xiàn)在有的小伙伴為了躲避中文亂碼的問題甚至代碼中不使用中文,注釋和提示都用英文,我曾經(jīng)也這樣干過,但這并不是解決問題,而是逃避問題,今天我們一起徹底解決 Python 中文亂碼的問題
    2020-02-02

最新評論