Simple Guide to Create a Tensor in PyTorch – PyTorch Tutorial

By | April 7, 2022

It is easy to create a tensor in pytorch, for example:

4 Methods to Create a PyTorch Tensor – PyTorch Tutorial

In this tutorial, we will introduce a simple guide to how to do for beginners.

Guide 1: Use torch.tensor() to create a tensor with pre-existing data

We can use python list, numpy data to create a tensor, 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.LongTensor

Guide 1: Use torch.* to create a tensor with specific size

torch.* can be: torch.from_numpy(), torch.zeros(), torch.ones(), torch.rand().

For example:

x = torch.rand([5, 5])

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

We will get:

tensor([[0.1049, 0.1768, 0.4231, 0.1914, 0.4608],
        [0.3837, 0.5954, 0.4784, 0.4999, 0.0194],
        [0.3035, 0.5374, 0.2932, 0.1672, 0.4826],
        [0.6667, 0.0729, 0.6812, 0.6475, 0.4100],
        [0.3388, 0.0835, 0.1137, 0.9174, 0.7900]])
torch.FloatTensor

Guide 3: Use torch.*_like to create a tensor with the same size (and similar types) as another tensor

torch.*_like can be: torch.zeros_like(), torch.ones_like(), torch.randn_like() et al.

For example:

x = torch.rand([5, 5])
z = torch.ones_like(x)
print(z)

We will get:

tensor([[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]])

Guide 4: Use tensor.new_* to create a tensor with similar type but different size as another tensor

These functions can be: Tensor.new_ones(), Tensor.new_zeros() and Tensor.new_tensor() et al.

For example:

x = torch.rand([5, 5])
print(x)
print(id(x))
z = x.new_tensor(x)
print(z)
print(id(z))

Run this code, we will see:

tensor([[0.9431, 0.6081, 0.5298, 0.3265, 0.4942],
        [0.6717, 0.2046, 0.8827, 0.2586, 0.2210],
        [0.2397, 0.8343, 0.0290, 0.3878, 0.2838],
        [0.9583, 0.0074, 0.8956, 0.9327, 0.6328],
        [0.3078, 0.3794, 0.9236, 0.5510, 0.5811]])
139939639180744
tensor([[0.9431, 0.6081, 0.5298, 0.3265, 0.4942],
        [0.6717, 0.2046, 0.8827, 0.2586, 0.2210],
        [0.2397, 0.8343, 0.0290, 0.3878, 0.2838],
        [0.9583, 0.0074, 0.8956, 0.9327, 0.6328],
        [0.3078, 0.3794, 0.9236, 0.5510, 0.5811]])
139939639180240

The value of x and z are the same, however, their addresses are different.

Leave a Reply