Search code examples
imageconv-neural-networkpredictionpytorch-dataloader

Am getting error trying to predict on a single image CNN pytorch


Error message

Traceback (most recent call last): File "pred.py", line 134, in output = model(data) Runtime Error: Expected 4-dimensional input for 4-dimensional weight [16, 3, 3, 3], but got 3-dimensional input of size [1, 32, 32] instead.

Prediction code

normalize = transforms.Normalize(mean=[0.4914, 0.4824, 0.4467],
                                     std=[0.2471, 0.2435, 0.2616])
train_set = transforms.Compose([
                                 transforms.RandomCrop(32, padding=4),
                                 transforms.RandomHorizontalFlip(),
                                 transforms.ToTensor(),
                                 normalize,
                                     ])

model = models.condensenet(args)
model = nn.DataParallel(model)
PATH = "results/savedir/save_models/checkpoint_001.pth.tar"

model.load_state_dict(torch.load(PATH)['state_dict'])


device = torch.device("cpu")

model.eval()

image = Image.open("horse.jpg")
input = train_set(image)
train_loader = torch.utils.data.DataLoader(
        input,
        batch_size=1,shuffle=True, num_workers=1)
for i, data in enumerate(train_loader):
    
    #input_var = torch.autograd.Variable(data, volatile=True)
    #input_var = input_var.view(1, 3, 32,32)
    
    **output = model(data)
topk=(1,5)
maxk = max(topk)

_, pred = output.topk(maxk, 1, True, True)
    

Am getting this error when am trying to predict on a single image Image shape/size error message

Link to saved model

Training code repository


Solution

  • Instead of doing the for loop and train_loader, solved this by just passing the input directly into the model. like this

    input = train_set(image)
    input = input.unsqueeze(0)
    model.eval()
    output = model(input)
    

    More details can be found here link