Get The PyTorch Variable Shape

Get the PyTorch Variable shape by using the PyTorch size operation

Type: FREE   By: Sebastian Gutierrez, AIWorkbox.com Instructor Sebastian Gutierrez   Duration: 1:56   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


Transcript:

First, we import PyTorch.

import torch


Then we print the PyTorch version we are using.

print(torch.__version__)

We are using PyTorch 0.3.1.post2.


Then because we’re going to be using a PyTorch variable, we import the variable functionality from the PyTorch autograd package.

from torch.autograd import Variable


Let’s now create our example PyTorch variable full of random floating point numbers.

random_variable_ex = Variable(torch.rand(2, 4, 6), requires_grad=True)

So we use Variable with a capital V.

Then we’re going to use torch.rand.

We pass in the shape of 2x4x6

We’re going to set requires_grad=True to make sure that we’re keeping track of all our operations.

And we’re going to set that whole thing to the Python variable random_variable_ex.


Let’s print the random_variable_ex Python variable to see what we have.

print(random_variable_ex)

We see that it’s a PyTorch floating tensor.

We see that the size is 2x4x6.

And that makes sense because we defined the variable that way.


However, some time you may adjust some data and you need to get the shape of the PyTorch variable.

So let’s check to see what we can do.


First, let’s check that it actually is a PyTorch variable.

type(random_variable_ex)

So we use type, and then we pass in our random_variable_ex.

We see that the class is torch.autograd.variable.Variable with a capital V.


Now, let’s get the PyTorch variable shape by using the size operation.

random_variable_ex.size()

We see that it’s torch.Size.

It’s 2x4x6.

We can see that it returned a PyTorch tensor size object that has the array of 2, 4, 6.


To get the actual integers from this size object, we can use Python’s list functionality.

random_variable_size_list = list(random_variable_ex.size())

So we pass our random_variable_ex, we say (.size), and we pass that to the Python list functionality, and we’re going to assign that to the random_variable_size_list Python variable.


Then we print the random_variable_size_list variable to see what we get.

print(random_variable_size_list)

We see that it is a list that is 2, 4, 6, which is great and it matches up with what we got here.


Perfect - We were able to get the PyTorch variable shape by using the PyTorch size operation.



Back to deep learning tutorial lesson list