Learn practical skills, build real-world projects, and advance your career

Important functions of Pytorch - Tensor Basics

The torch package contains data structures for multi-dimensional tensors and mathematical operations over these are defined. Additionally, it provides many utilities for efficient serializing of Tensors and arbitrary types, and other useful utilities.

It has a CUDA counterpart, that enables you to run your tensor computations on an NVIDIA GPU with compute capability >= 3.0

  • torch.empty() => Returns a tensor filled with uninitialized data.
  • torch.rand() => Returns a tensor filled with random numbers from a uniform distribution on the interval [0, 1)
  • torch.tensor() => Constructs a tensor with data.
  • torch.eye() => Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. (or in other word it will give identity matrix in the form of tensor)
  • torch.narrow() => Returns a new tensor that is a narrowed version of input tensor.

Before we begin, let's install and import PyTorch

# Uncomment and run the appropriate command for your operating system, if required

# Linux / Binder
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# Windows
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# MacOS
# !pip install numpy torch torchvision torchaudio
# Import torch and other required modules
import torch

Function 1 - torch.empty()

Returns a tensor filled with uninitialized data.


torch.empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor

Returns a tensor filled with uninitialized data. The shape of the tensor is defined by the variable argument size.

Parameters

size (int...) – a sequence of integers defining the shape of the output tensor.Can be a variable number of arguments or a collection like a list or tuple.

# Example 1 - working
x=torch.empty(3)
print(x)
tensor([4.3961e-35, 0.0000e+00, 1.4013e-45])