【问题标题】:Simple way to evaluate Pytorch torchvision on a single image在单个图像上评估 Pytorch torchvision 的简单方法
【发布时间】:2019-12-01 21:06:11
【问题描述】:

我在 Pytorch v1.3、torchvision v0.4.2 上有一个预训练模型,如下所示:

import PIL, torch, torchvision
# Load and normalize the image
img_file = "./robot_image.jpg"
img = PIL.Image.open(img_file)
img = torchvision.transforms.ToTensor()((img))
img = 0.5 + 0.5 * (img - img.mean()) / img.std()

# Load a pre-trained network and compute its prediction
alexnet = torchvision.models.alexnet(pretrained=True)

我想测试这张单张图片,但出现错误:

alexnet(img)
RuntimeError: Expected 4-dimensional input for 4-dimensional weight 64 3 11 11, but got 3-dimensional input of size [3, 741, 435] instead

让模型评估单个数据点的最简单和惯用的方法是什么?

【问题讨论】:

    标签: pytorch torchvision


    【解决方案1】:

    AlexNet 期望一个 4 维大小的张量(batch_size x 通道 x 高度 x 宽度)。您提供的是 3 维张量。

    要将张量更改为 (1, 3, 741, 435) 大小,只需添加以下行:

    img = img.unsqueeze(0)
    

    您还需要对图像进行下采样,因为 AlexNet 期望输入的高度和宽度为 224x224。

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 2022-01-07
      • 2019-02-12
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 2012-05-08
      • 2022-07-28
      相关资源
      最近更新 更多