所有内容都在标题中,我只想知道,如何在pytorch中加载我自己的测试数据(image.jpg),以测试我的CNN。
答案 0 :(得分:0)
您需要像在训练中一样将图像馈入网络:也就是说,您应该应用完全相同的变换以获得相似的结果。
假设您的网络是使用this code(或类似方法)训练的,则可以看到(用于验证的)输入图像经历了以下transformations:
transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ])),
在torchvision.transforms
文档之后,您可以看到输入图像通过了:
[0, 1]
范围内,并转置为3×224×224数组您可以手动对所有图像进行
import numpy as np
from PIL import Image
pil_img = Image.open('image.jpg').resize((256, 256), Image.BILINEAR) # read and resize
# center crop
w, h = pil_img.size
i = int(round((h - 224) / 2.))
j = int(round((w - 224) / 2.))
pil_img = pil_img.crop((j, i, j+224, i+224))
np_img = np.array(pil_img).astype(np.float32) / 255.
np_img = np.transpose(np_img, (2, 0, 1))
# normalize
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
for c in range(3):
np_img = (np_img[c, ...] - mean[c]) / std[c]
一旦np_img
为模型准备就绪,就可以运行前馈传递:
pred = model(np_img[None, ...]) # note that we add a singleton leading dim for batch
答案 1 :(得分:0)
感谢您的回复。我的问题是加载测试数据,并且我找到了解决方案。
test_data = datasets.ImageFolder('root/test_cnn', transform=transform)
例如,如果我有2个目录cat&dog(在test_cnn目录中)包含图像,则Object ImageFolder将自动为我的图像分配cat和dog类。
在测试期间,我只需要删除类。