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

yipeiwu_com7年前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设计】。

相关文章

Centos 升级到python3后pip 无法使用的解决方法

一. 问题 [root@localhost local]# pip -bash: pip: command not found pip无法使用. 二. 系统环境 Centos...

python如何通过protobuf实现rpc

python如何通过protobuf实现rpc

由于项目组现在用的rpc是基于google protobuf rpc协议实现的,所以花了点时间了解下protobuf rpc。rpc对于做分布式系统的人来说肯定不陌生,对于rpc不了解的...

linux平台使用Python制作BT种子并获取BT种子信息的方法

本文实例讲述了linux平台使用Python制作BT种子并获取BT种子信息的方法。分享给大家供大家参考,具体如下: 最近研究了一下linux BT服务器环境的搭建,需要在linux下制作...

Python测试Kafka集群(pykafka)实例

生产者代码: # -* coding:utf8 *- from pykafka import KafkaClient host = 'IP:9092, IP:9092, IP...

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

本文讲述了Python使用pip安装报错:is not a supported wheel on this platform的解决方法。分享给大家供大家参考,具体如下: 可能的原因1:安...