https://mp.weixin.qq.com/s/U80uqeP-_nRJTjJZ3MfQ4g
本文僅作為學(xué)術(shù)分享豺鼻,如果侵權(quán),會刪文處理
作者:澀醉
https://www.zhihu.com/question/68384370/answer/751212803
- 通過pytorch的hook機制簡單實現(xiàn)了一下,只輸出conv層的特征圖。
import torch
from torchvision.models import resnet18
import torch.nn as nn
from torchvision import transforms
import matplotlib.pyplot as plt
def viz(module, input):
x = input[0][0]
#最多顯示4張圖
min_num = np.minimum(4, x.size()[0])
for i in range(min_num):
plt.subplot(1, 4, i+1)
plt.imshow(x[i])
plt.show()
import cv2
import numpy as np
def main():
t = transforms.Compose([transforms.ToPILImage(),
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = resnet18(pretrained=True).to(device)
for name, m in model.named_modules():
# if not isinstance(m, torch.nn.ModuleList) and \
# not isinstance(m, torch.nn.Sequential) and \
# type(m) in torch.nn.__dict__.values():
# 這里只對卷積層的feature map進行顯示
if isinstance(m, torch.nn.Conv2d):
m.register_forward_pre_hook(viz)
img = cv2.imread('/Users/edgar/Desktop/cat.jpeg')
img = t(img).unsqueeze(0).to(device)
with torch.no_grad():
model(img)
if __name__ == '__main__':
main()
-
打印的特征圖大概是這個樣子广辰,取了第一層以及第四層的特征圖。
作者:袁坤
https://www.zhihu.com/question/68384370/answer/419741762
- 建議使用hook主之,在不改變網(wǎng)絡(luò)forward函數(shù)的基礎(chǔ)上提取所需的特征或者梯度择吊,在調(diào)用階段對module使用即可獲得所需梯度或者特征。
inter_feature = {}
inter_gradient = {}
def make_hook(name, flag):
if flag == 'forward':
def hook(m, input, output):
inter_feature[name] = input
return hook
elif flag == 'backward':
def hook(m, input, output):
inter_gradient[name] = output
return hook
else:
assert False
m.register_forward_hook(make_hook(name, 'forward'))
m.register_backward_hook(make_hook(name, 'backward'))
- 在前向計算和反向計算的時候即可達到類似鉤子的作用槽奕,中間變量已經(jīng)被放置于inter_feature 和 inter_gradient几睛。
output = model(input) # achieve intermediate feature
loss = criterion(output, target)
loss.backward() # achieve backward intermediate gradients
- 最后可根據(jù)需求是否釋放hook。hook.remove()
作者:羅一成
https://www.zhihu.com/question/68384370/answer/263120790
- 提取中間特征是指把中間的weights給提出來嗎?這樣不是直接訪問那個矩陣不就好了嗎? pytorch在存參數(shù)的時候, 其實就是給所有的weights bias之類的起個名字然后存在了一個字典里面. 不然你看看state_dict.keys(), 找到相對應(yīng)的key拿出來就好了粤攒。
- 就算用modules下面的class, 你存模型的時候因為你的activation function上面本身沒有參數(shù), 所以也不會被存進去. 不然你可以試試在Sequential里面把relu換成sigmoid, 你還是可以把之前存的state_dict給load回去所森。不能說是慎用functional吧, 我覺得其他的設(shè)置是應(yīng)該分開也存一份的(假設(shè)你把這些當(dāng)做超參的話)