pytorch 获取层权重,对特定层注入hook, 提取中间层输出的方法

yipeiwu_com6年前Python基础

如下所示:

#获取模型权重
for k, v in model_2.state_dict().iteritems():
 print("Layer {}".format(k))
 print(v)

#获取模型权重
for layer in model_2.modules():
 if isinstance(layer, nn.Linear):
  print(layer.weight)
#将一个模型权重载入另一个模型
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 获取层权重,对特定层注入hook, 提取中间层输出的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python 快速实现CLI 应用程序的脚手架

Python 快速实现CLI 应用程序的脚手架

今天跟大家分享一下如何快速实现一个Python CLI应用程序的脚手架,之所以会做这个是因为当时需要做一个运维的小工具希望用命令行的方式来使用,但是搜遍网上很多资料都没有系统讲解从开发、...

Python内置的字符串处理函数详细整理(覆盖日常所用)

str='python String function' 生成字符串变量str='python String function' 字符串长度获取:len(str) 例:print '%s...

Python基于辗转相除法求解最大公约数的方法示例

Python基于辗转相除法求解最大公约数的方法示例

本文实例讲述了Python基于辗转相除法求解最大公约数的方法。分享给大家供大家参考,具体如下: 之前总结过一次高德纳TAOCP中的最大公约数求解,其实课后题中的算法修改要求实现的是辗转相...

python 实现矩阵填充0的例子

需求: 原矩阵 [[1 2 3] [4 5 6] [7 8 9]] 在原矩阵元素之间填充元素 0,得到 [[1. 0. 2. 0. 3.] [0. 0. 0. 0. 0....

pytorch: tensor类型的构建与相互转换实例

Summary 主要包括以下三种途径: 使用独立的函数; 使用torch.type()函数; 使用type_as(tesnor)将张量转换为给定类型的张量。 使用独立函数 impor...