【问题标题】:load test data in pytorch在pytorch中加载测试数据
【发布时间】:2019-04-22 02:57:12
【问题描述】:

全部在标题中,我只想知道,如何在pytorch中加载我自己的测试数据(image.jpg)来测试我的CNN。

【问题讨论】:

    标签: python python-3.x deep-learning conv-neural-network pytorch


    【解决方案1】:

    您需要像在训练中一样将图像提供给网络:也就是说,您应该应用完全相同的转换来获得相似的结果。

    假设您的网络是使用this code(或类似的)训练的,您可以看到输入图像(用于验证)经历了以下transformations

    transforms.Compose([
                transforms.Resize(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                normalize,
            ])),
    

    按照torchvision.transforms docs,您可以看到输入图像通过:

    • 调整为 256x256 像素
    • 从图片中心裁剪 224x224 矩形
    • 图像从 uint8 数据类型转换为 [0, 1] 范围内的浮点数,并转置为 3×224×224 数组
    • 图像是normalize,减去均值并除以标准。

    您可以对任何图像手动执行所有这些操作

    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
    

    【讨论】:

      【解决方案2】:

      感谢您的回复。我的问题是加载测试数据,我找到了解决方案

      test_data = datasets.ImageFolder('root/test_cnn', transform=transform)
      

      例如,如果我有 2 个包含图像的目录 cat 和 dog(在 test_cnn 目录中),Object ImageFolder 将自动为我的图像分配 cat 和 dog 类。

      在测试期间,我只需要放弃课程。

      【讨论】:

        猜你喜欢
        • 2017-09-12
        • 2020-08-07
        • 1970-01-01
        • 2021-03-27
        • 2021-03-21
        • 1970-01-01
        • 2021-07-21
        • 2021-03-31
        • 2021-08-25
        相关资源
        最近更新 更多