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

yipeiwu_com5年前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设计】。

相关文章

Bottle框架中的装饰器类和描述符应用详解

最近在阅读Python微型Web框架Bottle的源码,发现了Bottle中有一个既是装饰器类又是描述符的有趣实现。刚好这两个点是Python比较的难理解,又混合在一起,让代码有些晦涩难...

在python 不同时区之间的差值与转换方法

之前有个程序,里面有个时间部分是按照国内时区,也就是东八区,来写的,程序中定义了北京时间2点到八点进行检查;后面程序在国外机器上,例如说韩国,欧美等,执行的时候发现会有时间上的问题,因为...

python使用xpath中遇到:<Element a at 0x39a9a80>到底是什么?

前言 大家在学习python爬虫的过程中,会发现一个问题,语法我看完了,说的也很详细,我也认真看了,爬虫还是不会写,或者没有思路,所以我的所有文章都会从实例的角度来解析一些常见的问题和...

在Pytorch中计算卷积方法的区别详解(conv2d的区别)

在二维矩阵间的运算: class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=...

举例讲解Python设计模式编程中对抽象工厂模式的运用

举例讲解Python设计模式编程中对抽象工厂模式的运用

抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 优点:易于交换“产品系列”,只要更改相应的工厂即可。 缺点:建立产品的时候很繁琐,需要增加和修改很多东...