torch create tensor: Construct a PyTorch Tensor

torch create tensor - Create an uninitialized PyTorch Tensor and an initialized PyTorch Tensor

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

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 import PyTorch.

import torch

We’re going to print the torch version to see what version we’re using.


We’re using 0.2.0_4.

To construct a PyTorch tensor, we define a variable x and set it equal to torch.Tensor(5,1).

x = torch.Tensor(5, 1)

We can then print that tensor to see that it is a torch.FloatTensor of size 5x1.


It is uninitialized.

By default, the PyTorch tensors are created using floats.

We can create a second tensor, y, using torch.Tensor(1,5).

y = torch.Tensor(1, 5)

We can print the y tensor and it is a FloatTensor of size 1x5.


It is uninitialized.

Next, we define a tensor z and we set it equal to torch.Tensor(2, 2, 2).

This is going to be a three-dimensional tensor.

z = torch.Tensor(2, 2, 2)

When we print it, we can see that it is 2x2, 2x2, it is uninitialized, and that there are two of these matrices.


Again, it is torch.FloatTensor of size 2x2x2.

Here, we’re going to construct a random tensor variable and we’re going to use torch.rand(3, 3, 3).

What this does is it creates a tensor based on the arguments we passed.

So it’s going to be 3x3x3.

random_tensor = torch.rand(3, 3, 3)

And when we print it, you can see that it has numbers that are all floating numbers.


This rand function in PyTorch gives you a random number pulled from a uniform distribution from 0 to 1.

So you can see that all of the numbers here displayed are between 0 and 1.

Back to PyTorch Tutorial Lesson List