【发布时间】:2017-12-13 23:34:00
【问题描述】:
对于我找到的 pytorch 模型,this tutorial 解释了如何对图像进行分类。我尝试对初始模型应用相同的过程。但是,对于我加载的每张图片,模型都会失败
代码:
# some people need these three lines to make it work
#from torchvision.models.inception import model_urls
#name = 'inception_v3_google'
#model_urls[name] = model_urls[name].replace('https://', 'http://')
from torch.autograd import Variable
import torchvision
import requests
from torchvision import models, transforms
from PIL import Image
import io
from PIL import Image
LABELS_URL = 'https://s3.amazonaws.com/outcome-blog/imagenet/labels.json'
# cat
IMG_URL1 = 'http://farm2.static.flickr.com/1029/762542019_4f197a0de5.jpg'
# dog
IMG_URL2 = 'http://farm3.static.flickr.com/2314/2518519714_98b01968ee.jpg'
# lion
IMG_URL3 = 'http://farm1.static.flickr.com/62/218998565_62930f10fc.jpg'
labels = {int(key):value for (key, value)
in requests.get(LABELS_URL).json().items()}
model = torchvision.models.inception_v3(pretrained=True)
model.training = False
model.transform_input = False
def predict_url_img(url):
response = requests.get(url)
img_pil = Image.open(io.BytesIO(response.content))
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
preprocess = transforms.Compose([
transforms.Scale(256),
transforms.CenterCrop(299),
transforms.ToTensor(),
normalize
])
img_tensor = preprocess(img_pil)
img_tensor.unsqueeze_(0)
img_variable = Variable(img_tensor)
fc_out = model(img_variable)
print("prediction:", labels[fc_out.data.numpy().argmax()])
predict_url_img(IMG_URL1)
predict_url_img(IMG_URL2)
predict_url_img(IMG_URL3)
作为输出我得到这个:
('预测:', u"柱塞,水管工的助手")
('预测:', u'塑料袋')
('预测:', u"柱塞,水管工的助手")
【问题讨论】:
标签: pytorch