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

PyTorch Functions

Python APIs

In this post, we will learn about few of the various available creational PyTorch functions:

  • torch.as_tensor
  • torch.arange
  • torch.full & torch.full_like
  • torch.eye
  • torch.reshape
# Import torch and other required modules
import torch
import numpy as np

torch.as_tensor

Convert the data into a torch.Tensor. A torch.Tensor is a multi-dimensional matrix containing elements of a single data type.

# Example 1 - basic tensor
a = torch.tensor([[1, 2, 3, 4.]])
print(a)
b = np.array([1, 2, 3])
print(b)
c = torch.as_tensor(b)
c
tensor([[1., 2., 3., 4.]]) [1 2 3]
tensor([1, 2, 3])

As shown above, we have created a basic tensor and a numpy array. The numpy array can be converted into a tensor by using the torch.as_tensor method.