PyTorch torch.as_tensor() Method

PyTorch torch.as_tensor() method is “used to convert data to a tensor, sharing data and preserving autograd history if possible.”

Syntax

torch.as_tensor(data, dtype=None, device=None)

Parameters

  1. data (array_like): Initial data for the tensor. It can be a list, tuple, NumPy ndarray, scalar, and other types.
  2. dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: if None, infers data type from data.
  3. device (torch.device, optional): The device of the constructed tensor.

Example 1: Creating a tensor from an array

import numpy as np
import torch

# Creating a numpy array
numpy_array = np.array([1, 2, 3, 4, 5])

# Converting numpy array to a PyTorch tensor
tensor_from_numpy = torch.as_tensor(numpy_array)
print(tensor_from_numpy)

Output

tensor([1, 2, 3, 4, 5])

Example 2: Creating a tensor from a list

import torch

# Converting a list to a PyTorch tensor
list_data = [6, 7, 8, 9, 10]
tensor_from_list = torch.as_tensor(list_data)
print(tensor_from_list)

Output

tensor([ 6, 7, 8, 9, 10])

You can specify dtype and device arguments to torch.as_tensor() if you want the resulting tensor to have a specific data type or be on a specific device (like a GPU).

If you pass a tensor with the same dtype and device as desired, torch.as_tensor() doesn’t create a new tensor but simply returns the original one, making it efficient in such scenarios.

That’s it!

Related posts

torch.from_numpy()

torch.as_array()

Leave a Comment