Search code examples
pytorchtorch

Issue with running a single prediction with PyTorch


I have a trained model using PyTorch now I want to simpy run it on one example

>>> model
nn.Sequential {
  [input -> (0) -> (1) -> (2) -> (3) -> (4) -> (5) -> (6) -> (7) -> (8) -> (9) -> (10) -> output]
  (0): nn.SpatialConvolutionMap
  (1): nn.Tanh
  (2): nn.SpatialMaxPooling(2x2, 2, 2)
  (3): nn.SpatialConvolutionMap
  (4): nn.Tanh
  (5): nn.SpatialMaxPooling(2x2, 2, 2)
  (6): nn.Reshape(6400)
  (7): nn.Linear(6400 -> 128)
  (8): nn.Tanh
  (9): nn.Linear(128 -> 5)
  (10): nn.LogSoftMax
}

Then I load an image from my test set:

image = cv2.imread('image.png',cv2.IMREAD_GRAYSCALE)
transformation = transforms.Compose([transforms.ToTensor()]) 
image_tensor = transformation(image).float()
inp = Variable(image_tensor)

and finally try to run the network

output = model(inp) 

But I get error TypeError: 'Sequential' object is not callable


Solution

  • It seems like your model is not nn.Sequential (pytorch Sequential), but rather torch.legacy.nn.Sequential (a legacy lua torch model).
    Try using this model forward() explicitly:

    output = model.forward(inp[None, ...])  # don't forget to add "batch" dimension