【问题标题】:pytorch inception model outputs the wrong label for every input imagepytorch inception 模型为每个输入图像输出错误的标签
【发布时间】: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


    【解决方案1】:

    我发现在应用模型之前需要调用model.eval()。由于批量标准化和 dropout 层,模型在训练和测试方面的表现有所不同。

    【讨论】:

    • dropout 层也是如此,这两层在训练和测试阶段的行为不同,见here
    【解决方案2】:

    我执行了您的代码,添加了model.eval() 行并得到:

    ('prediction:', u'Egyptian cat')
    ('prediction:', u'groenendael')
    ('prediction:', u'lion, king of beasts, Panthera leo')
    

    但如果我更改预处理(仅删除您的 normalize 操作并设置 model.transform_input = True 以使用 PyTorch 中 Inception v3 的默认预处理)结果会略有不同:

    ('prediction:', u'tiger cat')
    ('prediction:', u'Border collie')
    ('prediction:', u'lion, king of beasts, Panthera leo')
    

    我不是猫狗专家,但快速的 Google 搜索表明这些结果更准确(您输入图片中的猫似乎更接近于 虎猫 而不是 埃及猫边境牧羊犬狗看起来比groenendael更类似于输入)。

    我的观点是,我认为应该使用 inception_v3 默认预处理(这是默认行为,除非您将其更改为 model.transform_input = False)而不是经典规范化,但我找不到关于此的明确答案。

    This thread 讨论了这个问题。

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 2022-08-03
      • 2011-09-30
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多