使用pytorch實(shí)現(xiàn)可視化中間層的結(jié)果
摘要
一直比較想知道圖片經(jīng)過(guò)卷積之后中間層的結(jié)果,于是使用pytorch寫(xiě)了一個(gè)腳本查看,先看效果
這是原圖,隨便從網(wǎng)上下載的一張大概224*224大小的圖片,如下

網(wǎng)絡(luò)介紹
我們使用的VGG16,包含RULE層總共有30層可以可視化的結(jié)果,我們把這30層分別保存在30個(gè)文件夾中,每個(gè)文件中根據(jù)特征的大小保存了64~128張圖片
結(jié)果如下:
原圖大小為224224,經(jīng)過(guò)第一層后大小為64224*224,下面是第一層可視化的結(jié)果,總共有64張這樣的圖片:

下面看看第六層的結(jié)果
這層的輸出大小是 1128112*112,總共有128張這樣的圖片

下面是完整的代碼
import cv2
import numpy as np
import torch
from torch.autograd import Variable
from torchvision import models
#創(chuàng)建30個(gè)文件夾
def mkdir(path): # 判斷是否存在指定文件夾,不存在則創(chuàng)建
# 引入模塊
import os
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符號(hào)
path = path.rstrip("\\")
# 判斷路徑是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
# 判斷結(jié)果
if not isExists:
# 如果不存在則創(chuàng)建目錄
# 創(chuàng)建目錄操作函數(shù)
os.makedirs(path)
return True
else:
return False
def preprocess_image(cv2im, resize_im=True):
"""
Processes image for CNNs
Args:
PIL_img (PIL_img): Image to process
resize_im (bool): Resize to 224 or not
returns:
im_as_var (Pytorch variable): Variable that contains processed float tensor
"""
# mean and std list for channels (Imagenet)
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
# Resize image
if resize_im:
cv2im = cv2.resize(cv2im, (224, 224))
im_as_arr = np.float32(cv2im)
im_as_arr = np.ascontiguousarray(im_as_arr[..., ::-1])
im_as_arr = im_as_arr.transpose(2, 0, 1) # Convert array to D,W,H
# Normalize the channels
for channel, _ in enumerate(im_as_arr):
im_as_arr[channel] /= 255
im_as_arr[channel] -= mean[channel]
im_as_arr[channel] /= std[channel]
# Convert to float tensor
im_as_ten = torch.from_numpy(im_as_arr).float()
# Add one more channel to the beginning. Tensor shape = 1,3,224,224
im_as_ten.unsqueeze_(0)
# Convert to Pytorch variable
im_as_var = Variable(im_as_ten, requires_grad=True)
return im_as_var
class FeatureVisualization():
def __init__(self,img_path,selected_layer):
self.img_path=img_path
self.selected_layer=selected_layer
self.pretrained_model = models.vgg16(pretrained=True).features
#print( self.pretrained_model)
def process_image(self):
img=cv2.imread(self.img_path)
img=preprocess_image(img)
return img
def get_feature(self):
# input = Variable(torch.randn(1, 3, 224, 224))
input=self.process_image()
print("input shape",input.shape)
x=input
for index,layer in enumerate(self.pretrained_model):
#print(index)
#print(layer)
x=layer(x)
if (index == self.selected_layer):
return x
def get_single_feature(self):
features=self.get_feature()
print("features.shape",features.shape)
feature=features[:,0,:,:]
print(feature.shape)
feature=feature.view(feature.shape[1],feature.shape[2])
print(feature.shape)
return features
def save_feature_to_img(self):
#to numpy
features=self.get_single_feature()
for i in range(features.shape[1]):
feature = features[:, i, :, :]
feature = feature.view(feature.shape[1], feature.shape[2])
feature = feature.data.numpy()
# use sigmod to [0,1]
feature = 1.0 / (1 + np.exp(-1 * feature))
# to [0,255]
feature = np.round(feature * 255)
print(feature[0])
mkdir('./feature/' + str(self.selected_layer))
cv2.imwrite('./feature/'+ str( self.selected_layer)+'/' +str(i)+'.jpg', feature)
if __name__=='__main__':
# get class
for k in range(30):
myClass=FeatureVisualization('/home/lqy/examples/TRP.PNG',k)
print (myClass.pretrained_model)
myClass.save_feature_to_img()
以上這篇使用pytorch實(shí)現(xiàn)可視化中間層的結(jié)果就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
tensorflow的ckpt及pb模型持久化方式及轉(zhuǎn)化詳解
今天小編就為大家分享一篇tensorflow的ckpt及pb模型持久化方式及轉(zhuǎn)化詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
解決python大批量讀寫(xiě).doc文件的問(wèn)題
今天小編就為大家分享一篇解決python大批量讀寫(xiě).doc文件的問(wèn)題。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
解決Jupyter Notebook “signal only works&nb
這篇文章主要介紹了解決Jupyter Notebook “signal only works in main thread“問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
python3爬蟲(chóng)之設(shè)計(jì)簽名小程序
這篇文章主要為大家詳細(xì)介紹了python3爬蟲(chóng)之寫(xiě)為朋友設(shè)計(jì)簽名的小程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
python爬蟲(chóng)beautifulsoup解析html方法
這篇文章主要介紹了python爬蟲(chóng)beautifulsoup解析html方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
python實(shí)現(xiàn)在cmd窗口顯示彩色文字
今天小編就為大家分享一篇python實(shí)現(xiàn)在cmd窗口顯示彩色文字,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
python+matplotlib實(shí)現(xiàn)動(dòng)態(tài)繪制圖片實(shí)例代碼(交互式繪圖)
這篇文章主要介紹了python+matplotlib實(shí)現(xiàn)動(dòng)態(tài)繪制圖片實(shí)例代碼(交互式繪圖),小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
基于Python實(shí)現(xiàn)語(yǔ)音合成小工具
TTS(Text To Speech)是一種語(yǔ)音合成技術(shù),可以讓機(jī)器將輸入文本以語(yǔ)音的方式播放出來(lái),實(shí)現(xiàn)機(jī)器說(shuō)話的效果。本文將使用pyttsx3庫(kù)作為示范,編寫(xiě)一個(gè)語(yǔ)音合成小工具,感興趣的可以了解一下2022-12-12

