pytorch实现用Resnet提取特征并保存为txt文件的方法
作者:qq_32464407 时间:2023-04-10 17:21:09
接触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
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)
以下是提取一个文件夹下所有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)
另外最近发现一个很简单的提取不含FC层的网络的方法:
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
来源:https://blog.csdn.net/qq_32464407/article/details/79190197
标签:pytorch,Resnet,特征
0
投稿
猜你喜欢
PHP页面中文乱码分析
2024-05-13 09:23:19
python标准库sys和OS的函数使用方法与实例详解
2022-06-24 20:22:42
python面向对象基础之常用魔术方法
2021-08-20 20:08:59
总结网络IO模型与select模型的Python实例讲解
2021-10-16 22:09:41
MySQL之select、distinct、limit的使用
2024-01-22 04:41:20
MySQL查看和修改字符编码的实现方法
2024-01-26 00:20:22
详解nuxt路由鉴权(express模板)
2024-05-11 10:22:53
CSS布局之浮动(一)两列布局
2008-08-18 21:24:00
JS如何获取变量值
2008-05-18 12:52:00
利用PHP实现词法分析器与自定义语言
2024-05-02 17:33:35
Python使用剪切板的方法
2022-01-25 02:17:39
jupyter notebook运行命令显示[*](解决办法)
2022-02-19 01:23:10
Python爬虫框架之Scrapy中Spider的用法
2023-10-04 10:38:21
Python验证码识别的方法
2023-05-30 10:22:39
Python OpenCV对图像进行模糊处理详解流程
2022-05-16 03:54:19
浅析Django 接收所有文件,前端展示文件(包括视频,文件,图片)ajax请求
2023-03-30 14:35:25
python3 cookbook中常遇问题解答
2022-09-07 09:07:05
学习ASP和编程的28个观点
2008-06-27 12:57:00
在python tkinter界面中添加按钮的实例
2023-06-03 08:30:41
Python决策树和随机森林算法实例详解
2021-12-15 21:44:24