Pytorch提取模型特征向量保存至csv的例子

 更新时间:2020年01月03日 08:47:34   作者:朴素.无恙  
今天小编就为大家分享一篇Pytorch提取模型特征向量保存至csv的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

Pytorch提取模型特征向量

# -*- coding: utf-8 -*-
"""
dj
"""
import torch
import torch.nn as nn
import os
from torchvision import models, transforms
from torch.autograd import Variable 
import numpy as np
from PIL import Image 
import torchvision.models as models
import pretrainedmodels
import pandas as pd
class FCViewer(nn.Module):
 def forward(self, x):
  return x.view(x.size(0), -1)
class M(nn.Module):
 def __init__(self, backbone1, drop, pretrained=True):
  super(M,self).__init__()
  if pretrained:
   img_model = pretrainedmodels.__dict__[backbone1](num_classes=1000, pretrained='imagenet') 
  else:
   img_model = pretrainedmodels.__dict__[backbone1](num_classes=1000, pretrained=None)  
  self.img_encoder = list(img_model.children())[:-2]
  self.img_encoder.append(nn.AdaptiveAvgPool2d(1))
  self.img_encoder = nn.Sequential(*self.img_encoder)
  if drop > 0:
   self.img_fc = nn.Sequential(FCViewer())         
  else:
   self.img_fc = nn.Sequential(
    FCViewer())
 def forward(self, x_img):
  x_img = self.img_encoder(x_img)
  x_img = self.img_fc(x_img)
  return x_img 
model1=M('resnet18',0,pretrained=True)
features_dir = '/home/cc/Desktop/features' 
transform1 = transforms.Compose([
  transforms.Resize(256),
  transforms.CenterCrop(224),
  transforms.ToTensor()]) 
file_path='/home/cc/Desktop/picture'
names = os.listdir(file_path)
print(names)
for name in names:
 pic=file_path+'/'+name
 img = Image.open(pic)
 img1 = transform1(img)
 x = Variable(torch.unsqueeze(img1, dim=0).float(), requires_grad=False)
 y = model1(x)
 y = y.data.numpy()
 y = y.tolist()
 #print(y)
 test=pd.DataFrame(data=y)
 #print(test)
 test.to_csv("/home/cc/Desktop/features/3.csv",mode='a+',index=None,header=None)

jiazaixunlianhaodemoxing

import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import argparse
class ResidualBlock(nn.Module):
 def __init__(self, inchannel, outchannel, stride=1):
  super(ResidualBlock, self).__init__()
  self.left = nn.Sequential(
   nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False),
   nn.BatchNorm2d(outchannel),
   nn.ReLU(inplace=True),
   nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),
   nn.BatchNorm2d(outchannel)
  )
  self.shortcut = nn.Sequential()
  if stride != 1 or inchannel != outchannel:
   self.shortcut = nn.Sequential(
    nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False),
    nn.BatchNorm2d(outchannel)
   )

 def forward(self, x):
  out = self.left(x)
  out += self.shortcut(x)
  out = F.relu(out)
  return out

class ResNet(nn.Module):
 def __init__(self, ResidualBlock, num_classes=10):
  super(ResNet, self).__init__()
  self.inchannel = 64
  self.conv1 = nn.Sequential(
   nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
   nn.BatchNorm2d(64),
   nn.ReLU(),
  )
  self.layer1 = self.make_layer(ResidualBlock, 64, 2, stride=1)
  self.layer2 = self.make_layer(ResidualBlock, 128, 2, stride=2)
  self.layer3 = self.make_layer(ResidualBlock, 256, 2, stride=2)
  self.layer4 = self.make_layer(ResidualBlock, 512, 2, stride=2)
  self.fc = nn.Linear(512, num_classes)

 def make_layer(self, block, channels, num_blocks, stride):
  strides = [stride] + [1] * (num_blocks - 1) #strides=[1,1]
  layers = []
  for stride in strides:
   layers.append(block(self.inchannel, channels, stride))
   self.inchannel = channels
  return nn.Sequential(*layers)

 def forward(self, x):
  out = self.conv1(x)
  out = self.layer1(out)
  out = self.layer2(out)
  out = self.layer3(out)
  out = self.layer4(out)
  out = F.avg_pool2d(out, 4)
  out = out.view(out.size(0), -1)
  out = self.fc(out)
  return out


def ResNet18():

 return ResNet(ResidualBlock)

import os
from torchvision import models, transforms
from torch.autograd import Variable 
import numpy as np
from PIL import Image 
import torchvision.models as models
import pretrainedmodels
import pandas as pd
class FCViewer(nn.Module):
 def forward(self, x):
  return x.view(x.size(0), -1)
class M(nn.Module):
 def __init__(self, backbone1, drop, pretrained=True):
  super(M,self).__init__()
  if pretrained:
   img_model = pretrainedmodels.__dict__[backbone1](num_classes=1000, pretrained='imagenet') 
  else:
   img_model = ResNet18()
   we='/home/cc/Desktop/dj/model1/incption--7'
   # 模型定义-ResNet
   #net = ResNet18().to(device)
   img_model.load_state_dict(torch.load(we))#diaoyong  
  self.img_encoder = list(img_model.children())[:-2]
  self.img_encoder.append(nn.AdaptiveAvgPool2d(1))
  self.img_encoder = nn.Sequential(*self.img_encoder)
  if drop > 0:
   self.img_fc = nn.Sequential(FCViewer())         
  else:
   self.img_fc = nn.Sequential(
    FCViewer())
 def forward(self, x_img):
  x_img = self.img_encoder(x_img)
  x_img = self.img_fc(x_img)
  return x_img 
model1=M('resnet18',0,pretrained=None)
features_dir = '/home/cc/Desktop/features' 
transform1 = transforms.Compose([
  transforms.Resize(56),
  transforms.CenterCrop(32),
  transforms.ToTensor()]) 
file_path='/home/cc/Desktop/picture'
names = os.listdir(file_path)
print(names)
for name in names:
 pic=file_path+'/'+name
 img = Image.open(pic)
 img1 = transform1(img)
 x = Variable(torch.unsqueeze(img1, dim=0).float(), requires_grad=False)
 y = model1(x)
 y = y.data.numpy()
 y = y.tolist()
 #print(y)
 test=pd.DataFrame(data=y)
 #print(test)
 test.to_csv("/home/cc/Desktop/features/3.csv",mode='a+',index=None,header=None)

以上这篇Pytorch提取模型特征向量保存至csv的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • python光学仿真学习wxpython创建手速测试程序

    python光学仿真学习wxpython创建手速测试程序

    这篇文章主要介绍了python光学仿真学习使用wxpython创建一个手速测试程序示例的实现,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2021-10-10
  • 使用Atom支持基于Jupyter的Python开教程详解

    使用Atom支持基于Jupyter的Python开教程详解

    这篇文章主要介绍了使用Atom支持基于Jupyter的Python开发,Vscode虽然说也有连接Jupyter的工具,但是交互式的开发Hydrogen体验更好,需要的朋友可以参考下
    2021-08-08
  • Python扫描端口的实现

    Python扫描端口的实现

    这篇文章主要介绍了Python扫描端口的实现,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • Pytorch基本变量类型FloatTensor与Variable用法

    Pytorch基本变量类型FloatTensor与Variable用法

    今天小编就为大家分享一篇Pytorch基本变量类型FloatTensor与Variable用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • 在python项目的docker镜像里如何使用pdm管理依赖

    在python项目的docker镜像里如何使用pdm管理依赖

    在 DjangoStarter 项目中,我已经使用 pdm 作为默认的包管理器,不再直接使用 pip,所以部署的时候 dockerfile 和 docker-compose 配置需要修改一下,这篇文章主要介绍了在python项目的docker镜像里使用pdm管理依赖,需要的朋友可以参考下
    2024-08-08
  • python实现单目标、多目标、多尺度、自定义特征的KCF跟踪算法(实例代码)

    python实现单目标、多目标、多尺度、自定义特征的KCF跟踪算法(实例代码)

    这篇文章主要介绍了python实现单目标、多目标、多尺度、自定义特征的KCF跟踪算法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-01-01
  • python多线程对多核cpu的利用解析

    python多线程对多核cpu的利用解析

    这篇文章主要为大家介绍了python多线程对多核cpu的利用解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • Python Word文件自动化实战之简历筛选

    Python Word文件自动化实战之简历筛选

    本文将利用Python自动化做一个具有实操性的小练习,即通过读取简历来筛选出符合招聘条件的简历。文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-05-05
  • Python Paramiko创建文件目录并上传文件详解

    Python Paramiko创建文件目录并上传文件详解

    Paramiko是一个用于进行SSH2会话的Python库,它支持加密、认证和文件传输等功能,本文旨在详细指导新手朋友如何使用Python的Paramiko库来创建远程文件目录并上传文件,希望对大家有所帮助
    2024-10-10
  • PyCharm如何设置Console控制台输出自动换行

    PyCharm如何设置Console控制台输出自动换行

    这篇文章主要介绍了PyCharm如何设置Console控制台输出自动换行问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05

最新评论