欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用pytorch實(shí)現(xiàn)可視化中間層的結(jié)果

 更新時(shí)間:2019年12月30日 10:06:38   作者:xz1308579340  
今天小編就為大家分享一篇使用pytorch實(shí)現(xiàn)可視化中間層的結(jié)果,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

摘要

一直比較想知道圖片經(jīng)過卷積之后中間層的結(jié)果,于是使用pytorch寫了一個(gè)腳本查看,先看效果

這是原圖,隨便從網(wǎng)上下載的一張大概224*224大小的圖片,如下

網(wǎng)絡(luò)介紹

我們使用的VGG16,包含RULE層總共有30層可以可視化的結(jié)果,我們把這30層分別保存在30個(gè)文件夾中,每個(gè)文件中根據(jù)特征的大小保存了64~128張圖片

結(jié)果如下:

原圖大小為224224,經(jīng)過第一層后大小為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)文章

  • Python實(shí)現(xiàn)檢測(cè)文件MD5值的方法示例

    Python實(shí)現(xiàn)檢測(cè)文件MD5值的方法示例

    這篇文章主要介紹了Python實(shí)現(xiàn)檢測(cè)文件MD5值的方法,涉及Python針對(duì)大文件的讀取、判斷、運(yùn)算、加密等相關(guān)操作技巧,需要的朋友可以參考下
    2018-04-04
  • python使用pyaudio錄音和格式轉(zhuǎn)化方式

    python使用pyaudio錄音和格式轉(zhuǎn)化方式

    這篇文章主要介紹了python使用pyaudio錄音和格式轉(zhuǎn)化方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • 對(duì)PyQt5的輸入對(duì)話框使用(QInputDialog)詳解

    對(duì)PyQt5的輸入對(duì)話框使用(QInputDialog)詳解

    今天小編就為大家分享一篇對(duì)PyQt5的輸入對(duì)話框使用(QInputDialog)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • Python連接Oracle的多種方式小結(jié)

    Python連接Oracle的多種方式小結(jié)

    Oracle數(shù)據(jù)庫(kù)是一種強(qiáng)大的企業(yè)級(jí)關(guān)系數(shù)據(jù)庫(kù)管理系統(tǒng)(RDBMS),而Python是一門流行的編程語(yǔ)言,兩者的結(jié)合可以提供出色的數(shù)據(jù)管理和分析能力,本教程將詳細(xì)介紹如何在Python中連接Oracle數(shù)據(jù)庫(kù),需要的朋友可以參考下
    2024-08-08
  • 如何使用python socket模塊實(shí)現(xiàn)簡(jiǎn)單的文件下載

    如何使用python socket模塊實(shí)現(xiàn)簡(jiǎn)單的文件下載

    這篇文章主要介紹了如何使用python socket模塊實(shí)現(xiàn)簡(jiǎn)單的文件下載,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-09-09
  • 淺談Python3實(shí)現(xiàn)兩個(gè)矩形的交并比(IoU)

    淺談Python3實(shí)現(xiàn)兩個(gè)矩形的交并比(IoU)

    今天小編就為大家分享一篇淺談Python3實(shí)現(xiàn)兩個(gè)矩形的交并比(IoU),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Django之PopUp的具體實(shí)現(xiàn)方法

    Django之PopUp的具體實(shí)現(xiàn)方法

    今天小編就為大家分享一篇Django之PopUp的具體實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Python collections.defaultdict模塊用法詳解

    Python collections.defaultdict模塊用法詳解

    這篇文章主要介紹了Python collections.defaultdict模塊用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • pytorch中的squeeze函數(shù)、cat函數(shù)使用

    pytorch中的squeeze函數(shù)、cat函數(shù)使用

    這篇文章主要介紹了pytorch中的squeeze函數(shù)、cat函數(shù)使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python識(shí)別設(shè)備和操作系統(tǒng)神器device_detector使用探究

    Python識(shí)別設(shè)備和操作系統(tǒng)神器device_detector使用探究

    這篇文章主要介紹了Python識(shí)別設(shè)備和操作系統(tǒng)神器device_detector庫(kù)使用探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01

最新評(píng)論