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

使用pytorch提取卷積神經(jīng)網(wǎng)絡(luò)的特征圖可視化

 更新時間:2022年03月29日 11:20:22   作者:落櫻彌城  
這篇文章主要給大家介紹了關(guān)于使用pytorch提取卷積神經(jīng)網(wǎng)絡(luò)的特征圖可視化的相關(guān)資料,文中給出了詳細(xì)的思路以及示例代碼,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

前言

文章中的代碼是參考基于Pytorch的特征圖提取編寫的代碼本身很簡單這里只做簡單的描述。

1. 效果圖

先看效果圖(第一張是原圖,后面的都是相應(yīng)的特征圖,這里使用的網(wǎng)絡(luò)是resnet50,需要注意的是下面圖片顯示的特征圖是經(jīng)過放大后的圖,原圖是比較小的圖,因為太小不利于我們觀察):

2. 完整代碼

import os
import torch
import torchvision as tv
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
import argparse
import skimage.data
import skimage.io
import skimage.transform
import numpy as np
import matplotlib.pyplot as plt
import torchvision.models as models
from PIL import Image
import cv2

class FeatureExtractor(nn.Module):
    def __init__(self, submodule, extracted_layers):
        super(FeatureExtractor, self).__init__()
        self.submodule = submodule
        self.extracted_layers = extracted_layers
 
    def forward(self, x):
        outputs = {}
        for name, module in self.submodule._modules.items():
            if "fc" in name: 
                x = x.view(x.size(0), -1)
            
            x = module(x)
            print(name)
            if self.extracted_layers is None or name in self.extracted_layers and 'fc' not in name:
                outputs[name] = x

        return outputs


def get_picture(pic_name, transform):
    img = skimage.io.imread(pic_name)
    img = skimage.transform.resize(img, (256, 256))
    img = np.asarray(img, dtype=np.float32)
    return transform(img)

def make_dirs(path):
    if os.path.exists(path) is False:
        os.makedirs(path)


def get_feature():
    pic_dir = './images/2.jpg'
    transform = transforms.ToTensor()
    img = get_picture(pic_dir, transform)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    # 插入維度
    img = img.unsqueeze(0)

    img = img.to(device)

    
    net = models.resnet101().to(device)
    net.load_state_dict(torch.load('./model/resnet101-5d3b4d8f.pt'))
    exact_list = None
    dst = './feautures'
    therd_size = 256

    myexactor = FeatureExtractor(net, exact_list)
    outs = myexactor(img)
    for k, v in outs.items():
        features = v[0]
        iter_range = features.shape[0]
        for i in range(iter_range):
            #plt.imshow(x[0].data.numpy()[0,i,:,:],cmap='jet')
            if 'fc' in k:
                continue

            feature = features.data.numpy()
            feature_img = feature[i,:,:]
            feature_img = np.asarray(feature_img * 255, dtype=np.uint8)
            
            dst_path = os.path.join(dst, k)
            
            make_dirs(dst_path)
            feature_img = cv2.applyColorMap(feature_img, cv2.COLORMAP_JET)
            if feature_img.shape[0] < therd_size:
                tmp_file = os.path.join(dst_path, str(i) + '_' + str(therd_size) + '.png')
                tmp_img = feature_img.copy()
                tmp_img = cv2.resize(tmp_img, (therd_size,therd_size), interpolation =  cv2.INTER_NEAREST)
                cv2.imwrite(tmp_file, tmp_img)
            
            dst_file = os.path.join(dst_path, str(i) + '.png')
            cv2.imwrite(dst_file, feature_img)

if __name__ == '__main__':
    get_feature()

3. 代碼說明

下面的模塊是根據(jù)所指定的模型篩選出指定層的特征圖輸出,如果未指定也就是extracted_layers是None則以字典的形式輸出全部的特征圖,另外因為全連接層本身是一維的沒必要輸出因此進行了過濾。

class FeatureExtractor(nn.Module):
    def __init__(self, submodule, extracted_layers):
        super(FeatureExtractor, self).__init__()
        self.submodule = submodule
        self.extracted_layers = extracted_layers
 
    def forward(self, x):
        outputs = {}
        for name, module in self.submodule._modules.items():
            if "fc" in name: 
                x = x.view(x.size(0), -1)
            
            x = module(x)
            print(name)
            if self.extracted_layers is None or name in self.extracted_layers and 'fc' not in name:
                outputs[name] = x

        return outputs

這段主要是存儲圖片,為每個層創(chuàng)建一個文件夾將特征圖以JET的colormap進行按順序存儲到該文件夾,并且如果特征圖過小也會對特征圖放大同時存儲原始圖和放大后的圖。

for k, v in outs.items():
        features = v[0]
        iter_range = features.shape[0]
        for i in range(iter_range):
            #plt.imshow(x[0].data.numpy()[0,i,:,:],cmap='jet')
            if 'fc' in k:
                continue

            feature = features.data.numpy()
            feature_img = feature[i,:,:]
            feature_img = np.asarray(feature_img * 255, dtype=np.uint8)
            
            dst_path = os.path.join(dst, k)
            
            make_dirs(dst_path)
            feature_img = cv2.applyColorMap(feature_img, cv2.COLORMAP_JET)
            if feature_img.shape[0] < therd_size:
                tmp_file = os.path.join(dst_path, str(i) + '_' + str(therd_size) + '.png')
                tmp_img = feature_img.copy()
                tmp_img = cv2.resize(tmp_img, (therd_size,therd_size), interpolation =  cv2.INTER_NEAREST)
                cv2.imwrite(tmp_file, tmp_img)
            
            dst_file = os.path.join(dst_path, str(i) + '.png')
            cv2.imwrite(dst_file, feature_img)

這里主要是一些參數(shù),比如要提取的網(wǎng)絡(luò),網(wǎng)絡(luò)的權(quán)重,要提取的層,指定的圖像放大的大小,存儲路徑等等。

	net = models.resnet101().to(device)
    net.load_state_dict(torch.load('./model/resnet101-5d3b4d8f.pt'))
    exact_list = None#['conv1']
    dst = './feautures'
    therd_size = 256

4. 可視化梯度,feature

上面的辦法只是簡單的將經(jīng)過網(wǎng)絡(luò)計算的圖片的輸出的feature進行圖片,github上有將CNN的梯度等全部進行可視化的代碼:pytorch-cnn-visualizations,需要注意的是如果只是簡單的替換成自己的網(wǎng)絡(luò)可能無法運行,大概率會報model沒有features或者classifier等錯誤,這兩個是進行分類網(wǎng)絡(luò)定義時的Sequential,其實就是索引網(wǎng)絡(luò)的每一層,自己稍微修改用model.children()等方法進行替換即可,我自己修改之后得到的代碼grayondream-pytorch-visualization(本來想稍微封裝一下成為一個更加通用的結(jié)構(gòu),暫時沒時間以后再說吧!),下面是效果圖:

總結(jié)

到此這篇關(guān)于使用pytorch提取卷積神經(jīng)網(wǎng)絡(luò)的特征圖可視化的文章就介紹到這了,更多相關(guān)pytorch提取特征圖可視化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python中Scrapy?shell的使用

    python中Scrapy?shell的使用

    這篇文章主要介紹了python入門之Scrapy?shell的使用,scrapy提供了一個shell。用來方便的測試規(guī)則,下面我們一起進入文章學(xué)習(xí)該內(nèi)容吧,需要的小伙伴可以參考一下,希望對你有所幫助
    2022-02-02
  • PyTorch策略梯度算法詳情

    PyTorch策略梯度算法詳情

    這篇文章主要介紹了PyTorch策略梯度算法詳情,文章我們主要使用策略梯度算法解決CartPole問題,詳細(xì)的相關(guān)介紹,需要的朋友可以參考一下
    2022-07-07
  • Python入門之列表用法詳解

    Python入門之列表用法詳解

    列表是元素的集合,存儲在一個變量中。這篇文章主要為大家介紹一下Python中列表的定義與使用,文中的示例代碼講解詳細(xì),需要的可以參考一下
    2022-09-09
  • Flask框架debug與配置項的開啟與設(shè)置詳解

    Flask框架debug與配置項的開啟與設(shè)置詳解

    這篇文章主要介紹了Flask框架debug與配置項的開啟與設(shè)置,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-09-09
  • 用python寫一個定時提醒程序的實現(xiàn)代碼

    用python寫一個定時提醒程序的實現(xiàn)代碼

    今天小編就為大家分享一篇用python寫一個定時提醒程序的實現(xiàn)代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • Python 如何讀取.txt,.md等文本文件

    Python 如何讀取.txt,.md等文本文件

    這篇文章主要介紹了Python 讀取.txt,.md等文本文件的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python中的Request請求重試機制

    Python中的Request請求重試機制

    這篇文章主要介紹了Python中的Request請求重試機制,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • python正則表達式re.sub各個參數(shù)的超詳細(xì)講解

    python正則表達式re.sub各個參數(shù)的超詳細(xì)講解

    Python 的 re 模塊提供了re.sub用于替換字符串中的匹配項,下面這篇文章主要給大家介紹了關(guān)于python正則表達式re.sub各個參數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • tensorflow中Dense函數(shù)的具體使用

    tensorflow中Dense函數(shù)的具體使用

    本文主要介紹了tensorflow中Dense函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • 用uWSGI和Nginx部署Flask項目的方法示例

    用uWSGI和Nginx部署Flask項目的方法示例

    這篇文章主要介紹了用uWSGI和Nginx部署Flask項目的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05

最新評論

长兴县| 铜川市| 盱眙县| 黑河市| 甘德县| 巫溪县| 西藏| 海林市| 加查县| 华宁县| 西乌珠穆沁旗| 孙吴县| 上虞市| 金山区| 永吉县| 炎陵县| 德庆县| 西林县| 清涧县| 墨脱县| 宁乡县| 祁门县| 普兰店市| 安吉县| 本溪| 兴城市| 宜君县| 信阳市| 静海县| 大名县| 沐川县| 盘锦市| 思茅市| 商河县| 柞水县| 龙胜| 安义县| 澳门| 宜宾县| 莱州市| 龙州县|