PyTorch Variable: Create A PyTorch Variable

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

Type: FREE   By: Sebastian Gutierrez, Instructor Sebastian Gutierrez   Duration: 1:36   Technologies: PyTorch, Python

Page Sections: Video  |  Code  |  Transcript

< > Code:

You must be a Member to view code

Access all courses and lessons, gain confidence and expertise, and learn how things work and how to use them.

    or   Log In


We start by importing PyTorch.

import torch

Then we print the 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.


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.


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.


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.


Back to PyTorch Tutorial Lesson List