In the PyTorch deep learning model, all of your data inputs, outputs, and learning weights are going to be expressed as tensors. It is a multi-dimensional array that can contain floating-point integer or boolean data.

Initialize Tensors

In the previous tutorial, we initialize tensors from a Python list and NumPy array. In particular, in this tutorial, we’re going to only cover how to create empty PyTorch tensors.

We have the very simplest way to create a tensor is the torch.empty() method. PyTorch torch module has multiple factory methods that will let you create tensors with and without initial values and whatever datatype you need.

import torch

x=torch.empty(2,3,dtype=torch.float32)

print(type(x)) #<class 'torch.Tensor'>
print(x)
Output:
<class 'torch.Tensor'>
tensor([[-9.8166e-38,  4.3524e-41, -9.8166e-38],
        [ 4.3524e-41,  0.0000e+00,  0.0000e+00]])

This is the most basic way to allocate tensor. Here it’s going to create a 3×4 tensor and you can see that the object itself is of type torch.tensor.

When you create a tensor using torch.empty() you may see random-looking values in the output that’s because torch.empty() just allocates memory and does not write any values to it so whatever happened to be a memory at the time you allocated this tensor is what you’re going to see here.

Related Post

What is tensor in PyTorch?

How to change the PyTorch tensor type?

PyTorch Contiguous Tensor

Concatenates PyTorch tensors using Stack and Cat with Dimension