接觸pytorch一天,發(fā)現(xiàn)pytorch上手的確比TensorFlow更快??梢愿奖愕貙?shí)現(xiàn)用預(yù)訓(xùn)練的網(wǎng)絡(luò)提特征。
我們提供的服務(wù)有:成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、東港ssl等。為近1000家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的東港網(wǎng)站制作公司以下是提取一張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)