python保存模型 特征_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博客。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/260395.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/260395.shtml
英文地址,請注明出處:http://en.pswp.cn/news/260395.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Matlab畫圖-非常具體,非常全面

Matlab畫圖 強大的畫圖功能是Matlab的特點之中的一個,Matlab提供了一系列的畫圖函數,用戶不須要過多的考慮畫圖的細節,僅僅須要給出一些基本參數就能得到所需圖形,這類函數稱為高層畫圖函數。此外,Matlab還提供了直接對…

openfeign使用_Feign使用基于配置服務發現

之前寫了篇《Feign在實際項目中的應用實踐總結》Feign在實際項目中的應用實踐總結 - 沐風之境 - 博客園?www.cnblogs.com總結了在一般項目中如何使用Feign這個提升開發效率的利器。最近在看Feign的文檔的時候發現了之前遺漏的一些點,所以寫了這篇文章進行補充。pom…

Oracle按用戶進行統計信息更新

按用戶進行統計信息更新 PL/sqldev工具使用system用戶連接到oracle,打開命令窗口執行以下SQL,用戶名請根據實際情況進行更改: begin dbms_stats.gather_schema_stats( ownname > testuser, estimate_percent > dbms_stats.aut…

個人使命宣言

最近在閱讀《高效人士的7個習慣》,其中提到個人使命宣言,也就是個人的行為憲法,有了這個憲法我們在日常生活和工作中才能有法可循有法可依,才不至于在紛繁的社會中迷失自己。通過思考自我感覺制作個人使命宣言還是非常有用的&…

jq js json 轉字符串_JS中JSON對象和String之間的互轉及處理技巧

json:JavaScript 對象表示法(javascript Object Notation),其實JSON就是一個javaScript的對象(Object)而已。如有不清楚JSON,可以去w3cschool了解http://www.w3school.com.cn/json/1.在Javascript中新建一個字符串(JSON文本)。 var txt { &q…

php中__autoload()方法詳解

原文地址:http://www.php100.com/html/php/lei/2013/0905/5267.html[導讀] PHP在魔術函數__autoload()方法出現以前,如果你要在一個程序文件中實例化100個對象,那么你必須用include或者require包含進來100個類文件,或者你把這100個…

python讀取sql_從python讀取sql的實例方法

從python讀取sql的方法: 1、利用python內置的open函數讀入sql文件; 2、利用第三方庫pymysql中的connect函數連接mysql服務器; 3、利用第三方庫pandas中的read_sql方法讀取傳入的sql文件即可。 python 直接讀取 sql 文件,達到使用 …

我笨,但我不傻

2019獨角獸企業重金招聘Python工程師標準>>> 威哥說:很多朋友給我留言,在學習的過程中如何堅持下去,關于努力和目標,我想談談自己的理解,有不同見解的地方,歡迎留言跟我探討哈。 if(努力苦逼) r…

GNU make manual 翻譯( 一百零四)

繼續翻譯 4.7 Rules without Recipes or Prerequisites If a rule has no prerequisites or recipe, and the target of the rule is a nonexistent file, then make imagines this target to have been updated whenever its rule is run. This implies that all targets dep…

mysql 數字 除以 一萬_騰訊股票接口、和訊網股票接口、新浪股票接口、雪球股票數據、網易股票數據...

騰訊股票接口:大單數據http://stock.finance.qq.com/sstock/list/view/dadan.php?tjs&csz002451&max80&p1&opt10&o0opt10 11 12 13 分別對應成交額大于等于(100萬 200萬 500萬 1000萬)opt1,2,3,4,5,6,7,8 分別對應成交量大于等于(100手 200手 …

asp.net url傳值,彈窗

一,<a>標簽鏈接式傳值 1&#xff0c; <a href"News_list.aspx?ClassID<%#((DataRowView)Container.DataItem)["ClassID"]%>&Editor<%#((DataRowView)Container.DataItem)["Editor"]%>" >傳值</a> 2, <a&g…

windows下python視頻加速調節_Windows下python+ffmpeg實現批量提取、切割視頻中的音頻...

廢話不說&#xff0c;直接上代碼 #遍歷所有mp4文件名->文件名改為字母形式->fffmpeg批量提取音頻、切割音頻->改回中文名 import os import subprocess current os.getcwd() dirs os.listdir(current) for i in dirs: if os.path.splitext(i)[1] ".mp4":…

(轉)千萬別熬夜:身體器官晚上工作時間表一覽

原文連接&#xff1a;http://jiuyinguan.blog.163.com/blog/static/20907903720126801015713/ 任何試圖更改生物鐘的行為&#xff0c;都將給身體留下莫名其妙的疾病&#xff0c;20、30年之后再后悔&#xff0c;已經來不及了。 一、晚上9-11點為免疫系統&#xff08;淋巴&#x…

伯納德?羅森伯格先生參加華為技術2016首屆國際光電連接技術研討會

近日&#xff0c;來自羅森伯格德國總部的CTO首席技術官伯納德羅森伯格先生參加了由華為技術組織的2016首屆國際光電連接技術研討會。本屆研討會華為共邀請了來自全球的約十家著名光電技術領先廠家及合作伙伴參與&#xff0c;共同探討未來數十年的光纖電子技術發展方向并分享最新…

如何使用python效率_Python的5中提高效率的用法

任何編程語言的高級特征通常都是通過大量的使用經驗才發現的。比如你在編寫一個復雜的項目&#xff0c;并在 stackoverflow 上尋找某個問題的答案。然后你突然發現了一個非常優雅的解決方案&#xff0c;它使用了你從不知道的 Python 功能&#xff01;這種學習方式太有趣了&…

記“debug alipay”一事

背景&#xff1a;客戶支付成功&#xff0c;無法返回支付結果 查找原因&#xff0c;追蹤代碼: verified AlipayNotify.verify(params,alipayConfig.sign_type,alipayConfig.partner,alipayConfig.key,alipayConfig.input_charset); if (!verified) { Debug.logError("##…

Xamarin 跨移動端開發系列(01) -- 搭建環境、編譯、調試、部署、運行

&#xff08;本文是基于老版本的VS和Xamarin&#xff0c;而VS2017已經集成了Xamarin&#xff0c;所以&#xff0c;本文已經過時&#xff0c;最新的Xamarin開發介紹請參見 使用 Xamarin開發手機聊天程序 。&#xff09; 如果是.NET開發人員&#xff0c;想學習手機應用開發&#…

內網穿透 無需公網ip_無需端口映射、無需公網IP,60秒實現FTP服務遠程訪問

互聯網的一大特點是實現信息共享&#xff0c;其中文件傳輸是信息共享十分重要的內容之一。科技公司更是離不開它。銷售、庫存、客戶資料等等數據需要隨時共享同步。當需要考慮到文件傳輸安全、傳輸質量、傳輸穩定性、訪問控制等諸多因素時&#xff0c;FTP服務器就成了解決文件傳…

mysql查詢的時候會涉及到鎖_Mysql 查詢 鎖的問題?

以下五種方法可以快速定位全局鎖的位置&#xff0c;僅供參考。方法1&#xff1a;利用 metadata_locks 視圖此方法僅適用于 MySQL 5.7 以上版本&#xff0c;該版本 performance_schema 新增了 metadata_locks&#xff0c;如果上鎖前啟用了元數據鎖的探針(默認是未啟用的)&#x…

Clojure:導入lein項目到IntelliJ IDEA

首先&#xff0c;我們需要先創建一個lein項目&#xff08;廢話。。&#xff09; lein new [項目名稱] 然后生成Maven的pom.xml文件 cd [項目目錄]lein pom 最后&#xff0c;在InteliJ IDEA中選擇導入Maven項目&#xff0c;選擇剛剛生成的pom.xml文件即可。 轉載于:https://www.…