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.”


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


  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)


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)


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



Leave a Comment