Understand The Difference Between torch.Tensor and torch.tensor – PyTorch Tutorial

By | April 7, 2022

We can use torch.Tensor() and torch.tensor() to create tensors in pytorch. In this tutorial, we will discuss the difference between them.

torch.Tensor()

torch.Tensor is a torch class, it is the alias of torch.FloatTensor().

For example:

import torch

x = torch.Tensor([
                  [[1, 2], [3, 4]],
                  [[5, 6], [7, 8]],
                  [[9, 10], [11, 12]]
                 ])

print(x)
print(x.type())

Run this code, we will see:

tensor([[[ 1.,  2.],
         [ 3.,  4.]],

        [[ 5.,  6.],
         [ 7.,  8.]],

        [[ 9., 10.],
         [11., 12.]]])
torch.FloatTensor

However, we should notice how to create a scalar using torch.Tensor()

For example:

x = torch.Tensor(1)

print(x)

Run this code, we will see:

tensor([-3305.4824])

We can find the value of tensor x is not 1.0, which means we can not use it to create a scalar in pytorch.

torch.tensor()

torch.tensor() allows us to create a tensor with pre-existing data, such as python list, numpy ndarray. Here is a tutorial:

4 Methods to Create a PyTorch Tensor – PyTorch Tutorial

It is defined as:

torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False)

Here we can use data parameter to create a pytorch tensor.

Different from torch.Tensor(), we can use torch.tensor() to create a scalar number easily.

For example:

x = torch.tensor(1)

print(x)
print(x.type())

Run this code, we will see:

tensor(1)
torch.LongTensor

From above, we can find:

  • We can use torch.Tensor() and torch.tensor() to create tensors.
  • However, if you plan to create a scalar number in pytorch, torch.tensor() will a good choice.

Leave a Reply