pytorch 獲取層權(quán)重,對特定層注入hook, 提取中間層輸出的方法
更新時間:2019年08月17日 09:44:21 作者:青盞
今天小編就為大家分享一篇pytorch 獲取層權(quán)重,對特定層注入hook, 提取中間層輸出的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
如下所示:
#獲取模型權(quán)重
for k, v in model_2.state_dict().iteritems():
print("Layer {}".format(k))
print(v)
#獲取模型權(quán)重 for layer in model_2.modules(): if isinstance(layer, nn.Linear): print(layer.weight)
#將一個模型權(quán)重載入另一個模型
model = VGG(make_layers(cfg['E']), **kwargs)
if pretrained:
load = torch.load('/home/huangqk/.torch/models/vgg19-dcbb9e9d.pth')
load_state = {k: v for k, v in load.items() if k not in ['classifier.0.weight', 'classifier.0.bias', 'classifier.3.weight', 'classifier.3.bias', 'classifier.6.weight', 'classifier.6.bias']}
model_state = model.state_dict()
model_state.update(load_state)
model.load_state_dict(model_state)
return model
# 對特定層注入hook def hook_layers(model): def hook_function(module, inputs, outputs): recreate_image(inputs[0]) print(model.features._modules) first_layer = list(model.features._modules.items())[0][1] first_layer.register_forward_hook(hook_function)
#獲取層 x = someinput for l in vgg.features.modules(): x = l(x) modulelist = list(vgg.features.modules()) for l in modulelist[:5]: x = l(x) keep = x for l in modulelist[5:]: x = l(x)
# 提取vgg模型的中間層輸出
# coding:utf8
import torch
import torch.nn as nn
from torchvision.models import vgg16
from collections import namedtuple
class Vgg16(torch.nn.Module):
def __init__(self):
super(Vgg16, self).__init__()
features = list(vgg16(pretrained=True).features)[:23]
# features的第3,8,15,22層分別是: relu1_2,relu2_2,relu3_3,relu4_3
self.features = nn.ModuleList(features).eval()
def forward(self, x):
results = []
for ii, model in enumerate(self.features):
x = model(x)
if ii in {3, 8, 15, 22}:
results.append(x)
vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3'])
return vgg_outputs(*results)
以上這篇pytorch 獲取層權(quán)重,對特定層注入hook, 提取中間層輸出的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python?實現(xiàn)驅(qū)動AI機(jī)器人
這篇文章主要介紹了Python?實現(xiàn)驅(qū)動AI機(jī)器人,下文圍繞利用Python?實現(xiàn)驅(qū)動AI機(jī)器人的相關(guān)資料展開內(nèi)容,需要的小伙伴可以參考一下2022-02-02
Python使用requests xpath 并開啟多線程爬取西刺代理ip實例
這篇文章主要介紹了Python使用requests xpath 并開啟多線程爬取西刺代理ip實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
深入學(xué)習(xí)python的yield和generator
這篇文章主要為大家詳細(xì)介紹了python的yield和generator,針對python的生成器和yield關(guān)鍵字進(jìn)行深入學(xué)習(xí),感興趣的小伙伴們可以參考一下2016-03-03
使用keras實現(xiàn)BiLSTM+CNN+CRF文字標(biāo)記NER
這篇文章主要介紹了使用keras實現(xiàn)BiLSTM+CNN+CRF文字標(biāo)記NER,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

