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

Pytorch Tensor functions

Here are my five Tensor functions in Pytorch

  • torch.as_tensor
  • torch.arange
  • torch.reshape
  • torch.abs
  • torch.is_leaf
# Import torch and other required modules
import torch
import numpy as np

Function 1 - torch.as_tensor

In Pytorch the recommended way to build tensors are either using torch.tensor() and torch.as_tensor(). So what is the difference. torch.tensor() always copies the data where as torch.as_tensor() always tries to avoid copies of the data. This is especially useful if you have a numpy array and want to avoid copying the numpy array into a tensor. Let's see an example

# Example 1 
arr = np.array([1, 2, 3])
arr
array([1, 2, 3])
t = torch.tensor(arr)
print(t)
print(t.dtype)
tensor([1, 2, 3]) torch.int64