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

interesting torch.tensors Functions

An short introduction about PyTorch and about the chosen functions and some of Real Usage.

- torch.as_tensor(data, dtype=None) → Tensor
→ convert any array like data to torch tensor 

- torch.rand_like(input, *, dtype=None, require_grad=False) → Tensor
→ create random tensor values with a specific shape 

- torch.chunk(input, chunks, dim=0) → List of Tensors
→ chunking big array to list of arrays for efficient computing

- torch.eye(n, m=None, *, require_grade=False) → Tensor
→ create random tensor values with a specific shape 

- torch.reshape(input, shape) → Tensor
→ create random tensor values with a specific shape 

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.as_tensor(data)

you see earlier that you can convert numpy array to torch tensors by calling torch.from_numpy method but what if your data is a regular python list or what if the data an array like but not actual numpy array, will here torch.as_tensor comes in handy to convert that array like type of data to the efficient torch tensor

# Example 1 - python list to torch tensor
x = [1, 2, 3]
x_tensor = torch.as_tensor(x)
x_tensor
tensor([1, 2, 3])