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的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 基于pytorch的保存和加载模型参数的方法

    当我们花费大量的精力训练完网络,下次预测数据时不想再(有时也不必再)训练一次时,这时候torch.save(),torch.load()就要登场了. 保存和加载模型参数有两种方式: 方式一: torch.save(net.state_dict(),path): 功能:保存训练完的网络的各层参数(即weights和bias) 其中:net.state_dict()获取各层参数,path是文件存放路径(通常保存文件格式为.pt或.pth) net2.load_state_dict(torch.loa

  • Pytorch保存模型用于测试和用于继续训练的区别详解

    保存模型 保存模型仅仅是为了测试的时候,只需要 torch.save(model.state_dict, path) path 为保存的路径 但是有时候模型及数据太多,难以一次性训练完的时候,而且用的还是 Adam优化器的时候, 一定要保存好训练的优化器参数以及epoch state = { 'model': model.state_dict(), 'optimizer':optimizer.state_dict(), 'epoch': epoch } torch.save(state, pat

  • Pytorch之保存读取模型实例

    pytorch保存数据 pytorch保存数据的格式为.t7文件或者.pth文件,t7文件是沿用torch7中读取模型权重的方式.而pth文件是python中存储文件的常用格式.而在keras中则是使用.h5文件. # 保存模型示例代码 print('===> Saving models...') state = { 'state': model.state_dict(), 'epoch': epoch # 将epoch一并保存 } if not os.path.isdir('checkpoin

  • Pytorch 保存模型生成图片方式

    三通道数组转成彩色图片 img=np.array(img1) img=img.reshape(3,img1.shape[2],img1.shape[3]) img=(img+0.5)*255##img做过归一化处理,[-0.5,0.5] img_path='/home/isee/wei/image/imageset/result.jpg' img=cv2.merge(img) cv2.imwrite(img_path,img) 单通道数组转化成灰度图 Img_mask=np.array(img_

  • 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 to

  • 关于Pytorch中模型的保存与迁移问题

    目录 1 引言 2 模型的保存与复用 2.1 查看网络模型参数 2.2 载入模型进行推断 2.3 载入模型进行训练 2.4 载入模型进行迁移 3 总结 1 引言 各位朋友大家好,欢迎来到月来客栈.今天要和大家介绍的内容是如何在Pytorch框架中对模型进行保存和载入.以及模型的迁移和再训练.一般来说,最常见的场景就是模型完成训练后的推断过程.一个网络模型在完成训练后通常都需要对新样本进行预测,此时就只需要构建模型的前向传播过程,然后载入已训练好的参数初始化网络即可. 第2个场景就是模型的再训练过

  • pytorch实现用Resnet提取特征并保存为txt文件的方法

    接触pytorch一天,发现pytorch上手的确比TensorFlow更快.可以更方便地实现用预训练的网络提特征. 以下是提取一张jpg图像的特征的程序: # -*- coding: utf-8 -*- import os.path import torch import torch.nn as nn from torchvision import models, transforms from torch.autograd import Variable import numpy as np

  • 解决pytorch多GPU训练保存的模型,在单GPU环境下加载出错问题

    背景 在公司用多卡训练模型,得到权值文件后保存,然后回到实验室,没有多卡的环境,用单卡训练,加载模型时出错,因为单卡机器上,没有使用DataParallel来加载模型,所以会出现加载错误. 原因 DataParallel包装的模型在保存时,权值参数前面会带有module字符,然而自己在单卡环境下,没有用DataParallel包装的模型权值参数不带module.本质上保存的权值文件是一个有序字典. 解决方法 1.在单卡环境下,用DataParallel包装模型. 2.自己重写Load函数,灵活.

  • PyTorch 多GPU下模型的保存与加载(踩坑笔记)

    这几天在一机多卡的环境下,用pytorch训练模型,遇到很多问题.现总结一个实用的做实验方式: 多GPU下训练,创建模型代码通常如下: os.environ['CUDA_VISIBLE_DEVICES'] = args.cuda model = MyModel(args) if torch.cuda.is_available() and args.use_gpu: model = torch.nn.DataParallel(model).cuda() 官方建议的模型保存方式,只保存参数: tor

  • pytorch模型的保存和加载、checkpoint操作

    其实之前笔者写代码的时候用到模型的保存和加载,需要用的时候就去度娘搜一下大致代码,现在有时间就来整理下整个pytorch模型的保存和加载,开始学习把~ pytorch的模型和参数是分开的,可以分别保存或加载模型和参数.所以pytorch的保存和加载对应存在两种方式: 1. 直接保存加载模型 (1)保存和加载整个模型 # 保存模型 torch.save(model, 'model.pth\pkl\pt') #一般形式torch.save(net, PATH) # 加载模型 model = torc

  • PyTorch深度学习模型的保存和加载流程详解

    一.模型参数的保存和加载 torch.save(module.state_dict(), path):使用module.state_dict()函数获取各层已经训练好的参数和缓冲区,然后将参数和缓冲区保存到path所指定的文件存放路径(常用文件格式为.pt..pth或.pkl). torch.nn.Module.load_state_dict(state_dict):从state_dict中加载参数和缓冲区到Module及其子类中 . torch.nn.Module.state_dict()函数

  • PyTorch模型的保存与加载方法实例

    目录 模型的保存与加载 保存和加载模型参数 保存和加载模型参数与结构 总结 模型的保存与加载 首先,需要导入两个包 import torch import torchvision.models as models 保存和加载模型参数 PyTorch模型将学习到的参数存储在一个内部状态字典中,叫做state_dict.这可以通过torch.save方法来实现.我们导入预训练好的VGG16模型,并将其保存.我们将state_dict字典保存在model_weights.pth文件中. model =

  • 基于Pytorch SSD模型分析

    本文参考github上SSD实现,对模型进行分析,主要分析模型组成及输入输出大小.SSD网络结构如下图: 每输入的图像有8732个框输出; import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable #from layers import * from data import voc, coco import os base = { '300': [6

  • 教你用PyTorch部署模型的方法

    目录 导读 使用Docker安装 Handlers 导出你的模型 用模型进行服务 总结 导读 演示了使用PyTorch最近发布的新工具torchserve来进行PyTorch模型的部署. 最近,PyTorch推出了名为torchserve.的新生产框架来为模型提供服务.我们看一下今天的roadmap: 1.使用Docker安装 2.导出模型 3.定义handler 4.保存模型 为了展示torchserve,我们将提供一个经过全面训练的ResNet34进行图像分类的服务. 使用Docker安装

随机推荐