2

I am learning PyTorch for an image classification task, and I ran into code where someone used a PyTorch Variable() in their function for prediction:

def predict_image(image):
    image_tensor = test_transforms(image).float()
    image_tensor = image_tensor.unsqueeze_(0)
    input = Variable(image_tensor)
    input = input.to(device)
    output = model(input)
    index = output.data.cpu().numpy().argmax()
    return index

Why do they use Variable() here? (even though it works fine without it.)

iacob
  • 20,084
  • 6
  • 92
  • 119
Sudhanshu
  • 704
  • 1
  • 9
  • 24

1 Answers1

3

You can safely omit it. Variables are a legacy component of PyTorch, now deprecated, that used to be required for autograd:

Variable (deprecated)

WARNING

The Variable API has been deprecated: Variables are no longer necessary to use autograd with tensors. Autograd automatically supports Tensors with requires_grad set to True. Below please find a quick guide on what has changed:

  • Variable(tensor) and Variable(tensor, requires_grad) still work as expected, but they return Tensors instead of Variables.
iacob
  • 20,084
  • 6
  • 92
  • 119