最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

分享Pytorch獲取中間層輸出的3種方法

 更新時間:2022年03月09日 17:24:20   作者:我是蛋蛋  
這篇文章主要給大家分享了Pytorch獲取中間層輸出的3種方法,文章內(nèi)容介紹詳細,需要的小伙伴可以參考一下,希望對你的學習或工作有所幫助

【1】方法一:獲取nn.Sequential的中間層輸出

import torch
import torch.nn as nn
model = nn.Sequential(
? ? ? ? ? ? nn.Conv2d(3, 9, 1, 1, 0, bias=False),
? ? ? ? ? ? nn.BatchNorm2d(9),
? ? ? ? ? ? nn.ReLU(inplace=True),
? ? ? ? ? ? nn.AdaptiveAvgPool2d((1, 1)),
? ? ? ? )

# 假如想要獲得ReLu的輸出
x = torch.rand([2, 3, 224, 224])
for i in range(len(model)):
? ? x = model[i](x)
? ? if i == 2:
? ? ? ? ReLu_out = x
print('ReLu_out.shape:\n\t',ReLu_out.shape)
print('x.shape:\n\t',x.shape)

結(jié)果:

ReLu_out.shape:
  torch.Size([2, 9, 224, 224])
x.shape:
  torch.Size([2, 9, 1, 1])

【2】方法二:IntermediateLayerGetter

from collections import OrderedDict
?
import torch
from torch import nn
?
?
class IntermediateLayerGetter(nn.ModuleDict):
? ? """
? ? Module wrapper that returns intermediate layers from a model
? ? It has a strong assumption that the modules have been registered
? ? into the model in the same order as they are used.
? ? This means that one should **not** reuse the same nn.Module
? ? twice in the forward if you want this to work.
? ? Additionally, it is only able to query submodules that are directly
? ? assigned to the model. So if `model` is passed, `model.feature1` can
? ? be returned, but not `model.feature1.layer2`.
? ? Arguments:
? ? ? ? model (nn.Module): model on which we will extract the features
? ? ? ? return_layers (Dict[name, new_name]): a dict containing the names
? ? ? ? ? ? of the modules for which the activations will be returned as
? ? ? ? ? ? the key of the dict, and the value of the dict is the name
? ? ? ? ? ? of the returned activation (which the user can specify).
? ? """
? ??
? ? def __init__(self, model, return_layers):
? ? ? ? if not set(return_layers).issubset([name for name, _ in model.named_children()]):
? ? ? ? ? ? raise ValueError("return_layers are not present in model")
?
? ? ? ? orig_return_layers = return_layers
? ? ? ? return_layers = {k: v for k, v in return_layers.items()}
? ? ? ? layers = OrderedDict()
? ? ? ? for name, module in model.named_children():
? ? ? ? ? ? layers[name] = module
? ? ? ? ? ? if name in return_layers:
? ? ? ? ? ? ? ? del return_layers[name]
? ? ? ? ? ? if not return_layers:
? ? ? ? ? ? ? ? break
?
? ? ? ? super(IntermediateLayerGetter, self).__init__(layers)
? ? ? ? self.return_layers = orig_return_layers
?
? ? def forward(self, x):
? ? ? ? out = OrderedDict()
? ? ? ? for name, module in self.named_children():
? ? ? ? ? ? x = module(x)
? ? ? ? ? ? if name in self.return_layers:
? ? ? ? ? ? ? ? out_name = self.return_layers[name]
? ? ? ? ? ? ? ? out[out_name] = x
? ? ? ? return out
# example
m = torchvision.models.resnet18(pretrained=True)
# extract layer1 and layer3, giving as names `feat1` and feat2`
new_m = torchvision.models._utils.IntermediateLayerGetter(m,{'layer1': 'feat1', 'layer3': 'feat2'})
out = new_m(torch.rand(1, 3, 224, 224))
print([(k, v.shape) for k, v in out.items()])
# [('feat1', torch.Size([1, 64, 56, 56])), ('feat2', torch.Size([1, 256, 14, 14]))]

作用:

在定義它的時候注明作用的模型(如下例中的m)和要返回的layer(如下例中的layer1,layer3),得到new_m。

使用時喂輸入變量,返回的就是對應的layer

舉例:

m = torchvision.models.resnet18(pretrained=True)
?# extract layer1 and layer3, giving as names `feat1` and feat2`
new_m = torchvision.models._utils.IntermediateLayerGetter(m,{'layer1': 'feat1', 'layer3': 'feat2'})
out = new_m(torch.rand(1, 3, 224, 224))
print([(k, v.shape) for k, v in out.items()])

輸出結(jié)果:

[('feat1', torch.Size([1, 64, 56, 56])), ('feat2', torch.Size([1, 256, 14, 14]))]

【3】方法三:鉤子

class TestForHook(nn.Module):
? ? def __init__(self):
? ? ? ? super().__init__()

? ? ? ? self.linear_1 = nn.Linear(in_features=2, out_features=2)
? ? ? ? self.linear_2 = nn.Linear(in_features=2, out_features=1)
? ? ? ? self.relu = nn.ReLU()
? ? ? ? self.relu6 = nn.ReLU6()
? ? ? ? self.initialize()

? ? def forward(self, x):
? ? ? ? linear_1 = self.linear_1(x)
? ? ? ? linear_2 = self.linear_2(linear_1)
? ? ? ? relu = self.relu(linear_2)
? ? ? ? relu_6 = self.relu6(relu)
? ? ? ? layers_in = (x, linear_1, linear_2)
? ? ? ? layers_out = (linear_1, linear_2, relu)
? ? ? ? return relu_6, layers_in, layers_out

features_in_hook = []
features_out_hook = []

def hook(module, fea_in, fea_out):
? ? features_in_hook.append(fea_in)
? ? features_out_hook.append(fea_out)
? ? return None

net = TestForHook()

第一種寫法,按照類型勾,但如果有重復類型的layer比較復雜

net_chilren = net.children()
for child in net_chilren:
? ? if not isinstance(child, nn.ReLU6):
? ? ? ? child.register_forward_hook(hook=hook)

推薦下面我改的這種寫法,因為我自己的網(wǎng)絡中,在Sequential中有很多層,
這種方式可以直接先print(net)一下,找出自己所需要那個layer的名稱,按名稱勾出來

layer_name = 'relu_6'
for (name, module) in net.named_modules():
? ? if name == layer_name:
? ? ? ? module.register_forward_hook(hook=hook)

print(features_in_hook) ?# 勾的是指定層的輸入
print(features_out_hook) ?# 勾的是指定層的輸出

到此這篇關(guān)于分享Pytorch獲取中間層輸出的3種方法的文章就介紹到這了,更多相關(guān)Pytorch獲取中間層輸出方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 用Python爬取LOL所有的英雄信息以及英雄皮膚的示例代碼

    用Python爬取LOL所有的英雄信息以及英雄皮膚的示例代碼

    這篇文章主要介紹了用Python爬取LOL所有的英雄信息以及英雄皮膚的示例代碼,主要分為兩部分,獲取網(wǎng)頁上數(shù)據(jù)和圖片保存到本地等,感興趣的可以了解一下
    2020-07-07
  • 沒編程基礎(chǔ)可以學python嗎

    沒編程基礎(chǔ)可以學python嗎

    在本篇文章里小編給大家整理的是關(guān)于沒編程基礎(chǔ)可以學python嗎的相關(guān)知識點,需要的朋友們可以學習下。
    2020-06-06
  • Django中Middleware中的函數(shù)詳解

    Django中Middleware中的函數(shù)詳解

    這篇文章主要介紹了Django中Middleware中的函數(shù)詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • python 布爾操作實現(xiàn)代碼

    python 布爾操作實現(xiàn)代碼

    python布爾操作也是我們經(jīng)常寫代碼需要用到的,首先我們需要明白在python里面,哪些被解釋器當做真,哪些當做假
    2013-03-03
  • python爬取w3shcool的JQuery課程并且保存到本地

    python爬取w3shcool的JQuery課程并且保存到本地

    本文主要介紹python爬取w3shcool的JQuery的課程并且保存到本地的方法解析。具有很好的參考價值。下面跟著小編一起來看下吧
    2017-04-04
  • 基于python的MD5腳本開發(fā)思路

    基于python的MD5腳本開發(fā)思路

    這篇文章主要介紹了基于python的MD5腳本,通過 string模塊自動生成字典,使用permutations()函數(shù),對字典進行全排列,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2022-03-03
  • 關(guān)于Python數(shù)據(jù)處理中的None、NULL和NaN的理解與應用

    關(guān)于Python數(shù)據(jù)處理中的None、NULL和NaN的理解與應用

    這篇文章主要介紹了關(guān)于Python數(shù)據(jù)處理中的None、NULL和NaN的理解與應用,None表示空值,一個特殊Python對象,None的類型是NoneType,需要的朋友可以參考下
    2023-08-08
  • Python3.10和Python3.9版本之間的差異介紹

    Python3.10和Python3.9版本之間的差異介紹

    大家好,本篇文章主要講的是Python3.10和Python3.9版本之間的差異介紹,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下哦
    2021-12-12
  • Python Flask搭建yolov3目標檢測系統(tǒng)詳解流程

    Python Flask搭建yolov3目標檢測系統(tǒng)詳解流程

    YOLOv3沒有太多的創(chuàng)新,主要是借鑒一些好的方案融合到Y(jié)OLO里面。不過效果還是不錯的,在保持速度優(yōu)勢的前提下,提升了預測精度,尤其是加強了對小物體的識別能力
    2021-11-11
  • Python3實現(xiàn)打格點算法的GPU加速實例詳解

    Python3實現(xiàn)打格點算法的GPU加速實例詳解

    這篇文章主要給大家介紹了關(guān)于Python3實現(xiàn)打格點算法的GPU加速的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用python具有一定的參考學習價值,需要的朋友可以參考下
    2021-09-09

最新評論

周口市| 临泉县| 兴山县| 梓潼县| 依安县| 洛扎县| 湘阴县| 安康市| 通道| 榆林市| 涞水县| 崇州市| 陆丰市| 扎赉特旗| 青龙| 溧水县| 原平市| 乐亭县| 枝江市| 汝州市| 钦州市| 高清| 延庆县| 镇赉县| 屏边| 拉萨市| 临沧市| 阳信县| 海伦市| 弥渡县| 佛冈县| 陵川县| 清镇市| 金华市| 赤水市| 鄂托克前旗| 砚山县| 齐齐哈尔市| 屏南县| 通化县| 志丹县|