PyTorch Variable: Create A PyTorch Variable

PyTorch Variable - create a PyTorch Variable which wraps a PyTorch Tensor and records operations applied to it

PyTorch Variable - create a PyTorch Variable which wraps a PyTorch Tensor and records operations applied to it

Video Transcript


We start by importing PyTorch.

import torch


Then we print the torch version.

print(torch.__version__)

We see that we are using PyTorch 0.2.0_4.


Then we import the variable functionality from the PyTorch autograd package.

from torch.autograd import Variable


First, we’re going to create a random tensor example.

random_tensor_ex = (torch.rand(2, 3, 4) * 100).int()

So we'll use the PyTorch rand to create a 2x3x4 tensor.

We're going to multiply it by 100 and then cast it to an int.


We can then print that tensor to see what we created.

print(random_tensor_ex)

That way, we can see that it is 2x3x4 and we made it an integer tensor.

Here, we can see IntTensor so the numbers were easier to see.


When we check the type, we see that it is class torch.IntTensor.

type(random_tensor_ex)


Next, we’re going to define our random variable example.

random_variable_ex = Variable((torch.rand(2, 3, 4) * 100)
.int(), requires_grad=True)

We use Variable with a capital V and we define the tensor inside of it the same way.

We cast it to an int.

We specify requires_grad=True to make sure that we are keeping track of all the operations.


Then we can print our random variable example and we see that it looks exactly the same as the PyTorch IntTensors above.

print(random_variable_ex)

The only difference is that when we print it, the first line says “Variable containing:”


To make it more obvious, we can check the type of this variable and we see that it is the torch.autograd.variable.Variable with a capital V.

type(random_variable_ex)

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.