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


Posted in Python onAugust 17, 2019

如下所示:

#获取模型权重
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实现汉诺塔递归算法经典案例
Mar 01 Python
Python实现八大排序算法
Aug 13 Python
浅谈Pycharm中的Python Console与Terminal
Jan 17 Python
解决django后台样式丢失,css资源加载失败的问题
Jun 11 Python
python实现二分类的卡方分箱示例
Nov 22 Python
使用Pandas将inf, nan转化成特定的值
Dec 19 Python
python如何保存文本文件
Jun 07 Python
python和php哪个更适合写爬虫
Jun 22 Python
Python3爬虫关于识别检验滑动验证码的实例
Jul 30 Python
Python接口自动化测试的实现
Aug 28 Python
Python判断变量是否是None写法代码实例
Oct 09 Python
Python激活Anaconda环境变量的详细步骤
Jun 08 Python
关于PyTorch源码解读之torchvision.models
Aug 17 #Python
django项目用higcharts统计最近七天文章点击量
Aug 17 #Python
Django对models里的objects的使用详解
Aug 17 #Python
python3.6中@property装饰器的使用方法示例
Aug 17 #Python
对django的User模型和四种扩展/重写方法小结
Aug 17 #Python
python3.6编写的单元测试示例
Aug 17 #Python
python3 实现的对象与json相互转换操作示例
Aug 17 #Python
You might like
Zend的MVC机制使用分析(二)
2013/05/02 PHP
手把手教你打印出PDF(关于fpdf的简单应用)
2013/06/25 PHP
改写ThinkPHP的U方法使其路由下分页正常
2014/07/02 PHP
自己写的php curl库实现整站克隆功能
2015/02/12 PHP
laravel配置Redis多个库的实现方法
2019/04/10 PHP
PHP实现递归的三种方法
2020/07/04 PHP
纯CSS3实现质感细腻丝滑按钮
2021/03/09 HTML / CSS
javascript 面向对象编程基础:封装
2009/08/21 Javascript
用JQuery模仿淘宝的图片放大镜显示效果
2011/09/15 Javascript
原生js和jquery分别实现横向导航菜单效果
2016/05/13 Javascript
ReactNative踩坑之配置调试端口的解决方法
2017/07/28 Javascript
Vuejs在v-for中,利用index来对第一项添加class的方法
2018/03/03 Javascript
vue.js轮播图组件使用方法详解
2018/07/03 Javascript
Angular2中监听数据更新的方法
2018/08/31 Javascript
vue swipe自定义组件实现轮播效果
2019/07/03 Javascript
微信小程序引入模块中wxml、wxss、js的方法示例
2019/08/09 Javascript
解决layui动态加载复选框无法选中的问题
2019/09/20 Javascript
JavaScript获取当前url路径过程解析
2019/12/27 Javascript
[55:32]2018DOTA2亚洲邀请赛 4.4 淘汰赛 EG vs LGD 第二场
2018/04/05 DOTA
用Python编写一个基于终端的实现翻译的脚本
2015/04/24 Python
Python中MySQL数据迁移到MongoDB脚本的方法
2016/04/28 Python
Python生成8位随机字符串的方法分析
2017/12/05 Python
python 基于TCP协议的套接字编程详解
2019/06/29 Python
wxpython布局的实现方法
2019/11/01 Python
Python使用扩展库pywin32实现批量文档打印实例
2020/04/09 Python
python实现斗地主分牌洗牌
2020/06/22 Python
Python中random模块常用方法的使用教程
2020/10/04 Python
Ubuntu16安装Python3.9的实现步骤
2020/12/15 Python
斯凯奇美国官网:SKECHERS美国
2016/08/20 全球购物
加拿大时尚床上用品零售商:QE Home | Quilts Etc
2018/01/22 全球购物
Abbott Lyon官网:女士手表、珠宝及配件
2020/12/26 全球购物
爽歪歪广告词
2014/03/20 职场文书
教育专业毕业生推荐信
2014/07/10 职场文书
如何写股份合作协议书
2014/09/11 职场文书
Pytorch使用shuffle打乱数据的操作
2021/05/20 Python
Windows Server 2016 配置 IIS 的详细步骤
2022/04/28 Servers