pytorch實(shí)現(xiàn)用Resnet提取特征并保存為txt文件的方法
接觸pytorch一天,發(fā)現(xiàn)pytorch上手的確比TensorFlow更快??梢愿奖愕貙?shí)現(xiàn)用預(yù)訓(xùn)練的網(wǎng)絡(luò)提特征。
以下是提取一張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
from PIL import Image
features_dir = './features'
img_path = "hymenoptera_data/train/ants/0013035.jpg"
file_name = img_path.split('/')[-1]
feature_path = os.path.join(features_dir, file_name + '.txt')
transform1 = transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
transforms.ToTensor() ]
)
img = Image.open(img_path)
img1 = transform1(img)
#resnet18 = models.resnet18(pretrained = True)
resnet50_feature_extractor = models.resnet50(pretrained = True)
resnet50_feature_extractor.fc = nn.Linear(2048, 2048)
torch.nn.init.eye(resnet50_feature_extractor.fc.weight)
for param in resnet50_feature_extractor.parameters():
param.requires_grad = False
#resnet152 = models.resnet152(pretrained = True)
#densenet201 = models.densenet201(pretrained = True)
x = Variable(torch.unsqueeze(img1, dim=0).float(), requires_grad=False)
#y1 = resnet18(x)
y = resnet50_feature_extractor(x)
y = y.data.numpy()
np.savetxt(feature_path, y, delimiter=',')
#y3 = resnet152(x)
#y4 = densenet201(x)
y_ = np.loadtxt(feature_path, delimiter=',').reshape(1, 2048)
以下是提取一個(gè)文件夾下所有jpg、jpeg圖像的程序:
# -*- coding: utf-8 -*-
import os, torch, glob
import numpy as np
from torch.autograd import Variable
from PIL import Image
from torchvision import models, transforms
import torch.nn as nn
import shutil
data_dir = './hymenoptera_data'
features_dir = './features'
shutil.copytree(data_dir, os.path.join(features_dir, data_dir[2:]))
def extractor(img_path, saved_path, net, use_gpu):
transform = transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(224),
transforms.ToTensor() ]
)
img = Image.open(img_path)
img = transform(img)
x = Variable(torch.unsqueeze(img, dim=0).float(), requires_grad=False)
if use_gpu:
x = x.cuda()
net = net.cuda()
y = net(x).cpu()
y = y.data.numpy()
np.savetxt(saved_path, y, delimiter=',')
if __name__ == '__main__':
extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
files_list = []
sub_dirs = [x[0] for x in os.walk(data_dir) ]
sub_dirs = sub_dirs[1:]
for sub_dir in sub_dirs:
for extention in extensions:
file_glob = os.path.join(sub_dir, '*.' + extention)
files_list.extend(glob.glob(file_glob))
resnet50_feature_extractor = models.resnet50(pretrained = True)
resnet50_feature_extractor.fc = nn.Linear(2048, 2048)
torch.nn.init.eye(resnet50_feature_extractor.fc.weight)
for param in resnet50_feature_extractor.parameters():
param.requires_grad = False
use_gpu = torch.cuda.is_available()
for x_path in files_list:
print(x_path)
fx_path = os.path.join(features_dir, x_path[2:] + '.txt')
extractor(x_path, fx_path, resnet50_feature_extractor, use_gpu)
另外最近發(fā)現(xiàn)一個(gè)很簡單的提取不含F(xiàn)C層的網(wǎng)絡(luò)的方法:
resnet = models.resnet152(pretrained=True)
modules = list(resnet.children())[:-1] # delete the last fc layer.
convnet = nn.Sequential(*modules)
另一種更簡單的方法:
resnet = models.resnet152(pretrained=True) del resnet.fc
以上這篇pytorch實(shí)現(xiàn)用Resnet提取特征并保存為txt文件的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python實(shí)現(xiàn)手勢識(shí)別的示例(入門)
這篇文章主要介紹了python實(shí)現(xiàn)手勢識(shí)別的示例(入門),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
python之生產(chǎn)者消費(fèi)者模型實(shí)現(xiàn)詳解
這篇文章主要介紹了python之生產(chǎn)者消費(fèi)者模型實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
Python3使用TCP編寫一個(gè)簡易的文件下載器功能
這篇文章主要介紹了Python3使用TCP編寫一個(gè)簡易的文件下載器功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
Python實(shí)現(xiàn)批量替換Excel中字符
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)批量替換Excel中字符,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
python實(shí)現(xiàn)寫數(shù)字文件名的遞增保存文件方法
今天小編就為大家分享一篇python實(shí)現(xiàn)寫數(shù)字文件名的遞增保存文件方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10

