pytorch获取vgg16-feature层输出的例子

yipeiwu_com6年前Python基础

实际应用时可能比较想获取VGG中间层的输出,

那么就可以如下操作:

import numpy as np
import torch
from torchvision import models
from torch.autograd import Variable
import torchvision.transforms as transforms
 
 
class CNNShow():
  def __init__(self, model):
    self.model = model
    self.model.eval()
 
    self.created_image = self.image_for_pytorch(np.uint8(np.random.uniform(150, 180, (224, 224, 3))))
 
 
  def show(self):
    x = self.created_image
    for index, layer in enumerate(self.model):
      print(index,layer)
      x = layer(x)
 
  def image_for_pytorch(self,Data):
    transform = transforms.Compose([
      transforms.ToTensor(), # range [0, 255] -> [0.0,1.0]
      transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
    ]
    )
    imData = transform(Data)
    imData = Variable(torch.unsqueeze(imData, dim=0), requires_grad=True)
    return imData
 
if __name__ == '__main__':
 
  pretrained_model = models.vgg16(pretrained=True).features
  CNN = CNNShow(pretrained_model)
  CNN.show()

以上这篇pytorch获取vgg16-feature层输出的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现计算最小编辑距离

Python实现计算最小编辑距离

最小编辑距离或莱文斯坦距离(Levenshtein),指由字符串A转化为字符串B的最小编辑次数。允许的编辑操作有:删除,插入,替换。具体内容可参见:维基百科—莱文斯坦距离。一般代码实现的...

将string类型的数据类型转换为spark rdd时报错的解决方法

在将string类型的数据类型转换为spark rdd时,一直报这个错,StructType can not accept object %r in type %s” % (obj, t...

python科学计算之narray对象用法

python科学计算之narray对象用法

写在前面 最近在系统的看一些python科学计算开源包的内容,虽然以前是知道一些的,但都属于零零碎碎的,希望这次能把常用的一些函数、注意项整理下。小白的一些废话,高手请略过^ _ ^。文...

cProfile Python性能分析工具使用详解

cProfile Python性能分析工具使用详解

前言 Python自带了几个性能分析的模块:profile、cProfile和hotshot,使用方法基本都差不多,无非模块是纯Python还是用C写的。本文介绍cProfile。 例子...

Python产生Gnuplot绘图数据的方法

Python产生Gnuplot绘图数据的方法

gnuplot的绘图可以直接选取文件绘图,文件格式要求如下: x1 y1 x2 y2 ...... xn yn 在python中利用文件操作的write方法可以非常方便实现,在此记录一...