Why use Variable() in inference?

Viewed 288

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.)

1 Answers

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.
Related