Learn practical skills, build real-world projects, and advance your career
Updated 3 years ago
PyTorch package - some basic methods nice to know about
I picked the following 5 basic functions, where torch.randn is to create a sample tensor, torch.cat and torch.split to manipulate the created tensor, torch.numel and torch.is_nonzero to evaluate the resulting tensors.
- function 1: torch.is_nonzero
- function 2: torch.numel
- function 3: torch.randn
- function 4: torch.cat
- function 5: torch.split
Before we begin, let's install and import PyTorch
import torch
Function 1 - torch.is_nonzero(input) -> bool
torch.is_nonzero(input) -> (bool)
: Returns True if the input is a single element tensor which is not equal to zero after type conversions. i.e. not equal totorch.tensor([0.])
ortorch.tensor([0])
ortorch.tensor([False])
. Throws a RuntimeError iftorch.numel() != 1
(even in case of sparse tensors).
# Example 1 - working and returns True
x = torch.Tensor([3.]) # tensor with a single non-zero element
torch.is_nonzero(x)
True
An example of a tensor with a single non-zero element, which returns True.