PyTorch:使用torchvision.datasets.ImageFolder和DataLoader进行测试

时间:2018-03-02 16:56:42

标签: python pytorch

我是一个新手试图让这个PyTorch CNN与Cats&Dogs dataset from kaggle一起工作。由于没有测试图像的目标,我手动分类了一些测试图像,并将类放在文件名中,以便能够测试(也许应该只使用一些火车图像)。

我使用了torchvision.datasets.ImageFolder类来加载火车和测试图像。培训似乎有效。

但是我需要做些什么来使测试例程工作?我不知道,如何通过test_x和test_y将我的test_data_loader与底部的测试循环连接起来。

代码基于this MNIST example CNN.在那里,在创建加载器之后立即使用这样的东西。但我没有为我的数据集重写它:

test_x = Variable(torch.unsqueeze(test_data.test_data, dim=1), volatile=True).type(torch.FloatTensor)[:2000]/255.   # shape from (2000, 28, 28) to (2000, 1, 28, 28), value in range(0,1)
test_y = test_data.test_labels[:2000]

守则:

import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.utils.data as data
import torchvision
from torchvision import transforms

EPOCHS = 2
BATCH_SIZE = 10
LEARNING_RATE = 0.003
TRAIN_DATA_PATH = "./train_cl/"
TEST_DATA_PATH = "./test_named_cl/"
TRANSFORM_IMG = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(256),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225] )
    ])

train_data = torchvision.datasets.ImageFolder(root=TRAIN_DATA_PATH, transform=TRANSFORM_IMG)
train_data_loader = data.DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True,  num_workers=4)
test_data = torchvision.datasets.ImageFolder(root=TEST_DATA_PATH, transform=TRANSFORM_IMG)
test_data_loader  = data.DataLoader(test_data, batch_size=BATCH_SIZE, shuffle=True, num_workers=4) 

class CNN(nn.Module):
    # omitted...

if __name__ == '__main__':

    print("Number of train samples: ", len(train_data))
    print("Number of test samples: ", len(test_data))
    print("Detected Classes are: ", train_data.class_to_idx) # classes are detected by folder structure

    model = CNN()    
    optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
    loss_func = nn.CrossEntropyLoss()    

    # Training and Testing
    for epoch in range(EPOCHS):        
        for step, (x, y) in enumerate(train_data_loader):
            b_x = Variable(x)   # batch x (image)
            b_y = Variable(y)   # batch y (target)
            output = model(b_x)[0]          
            loss = loss_func(output, b_y)   
            optimizer.zero_grad()           
            loss.backward()                 
            optimizer.step()

            # Test -> this is where I have no clue
            if step % 50 == 0:
                test_x = Variable(test_data_loader)
                test_output, last_layer = model(test_x)
                pred_y = torch.max(test_output, 1)[1].data.squeeze()
                accuracy = sum(pred_y == test_y) / float(test_y.size(0))
                print('Epoch: ', epoch, '| train loss: %.4f' % loss.data[0], '| test accuracy: %.2f' % accuracy)

2 个答案:

答案 0 :(得分:6)

查看来自Kaggle和您的代码的数据,似乎您的数据加载存在问题,包括列车和测试集。首先,数据应该在每个标签的不同文件夹中,以便默认PyTorch ImageFolder正确加载它。在您的情况下,由于所有训练数据都在同一个文件夹中,因此PyTorch将其作为一个类加载,因此学习似乎正在起作用。您可以使用文件夹结构来更正此问题,例如 - train/dog, - train/cat, - test/dog, - test/cat,然后将火车和测试文件夹传递到火车上分别测试ImageFolder。训练代码似乎很好,只需更改文件夹结构,你应该很好。请查看ImageFolder的官方文档,其中有类似示例。

答案 1 :(得分:0)

根据上面@Monster的评论,这是我的ImageFolder文件夹结构

enter image description here

这就是我加载数据集的方式:

    train_dataset=datasets.ImageFolder(root="./root/",transform=train_transforms)