We import PyTorch.
import torch
We’re going to print the torch version to see what version we’re using.
print(torch.__version__)
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.
print(x)
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.
print(y)
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.
print(z)
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.
print(random_tensor)
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.