PyTorch torch.asarray() Method

PyTorch torch.asarray() method is “used to convert an object to a tensor.”

The object can be one of the following:

  1. a tensor
  2. a NumPy array or a NumPy scalar
  3. a DLPack capsule
  4. an object that implements Python’s buffer protocol
  5. a scalar
  6. a sequence of scalars


torch.asarray(obj, *, dtype=None, device=None, copy=None, requires_grad=False)


  1. obj (object): It is a tensor, NumPy array, DLPack Capsule object that implements Python’s buffer protocol, scalar, or sequence of scalars
  2. dtype (torch.dtype, optional):  The data type of the returned tensor. Default: None.
  3. copy (bool, optional): It controls whether the returned tensor shares memory with obj. Default: None.
  4. device (torch.device, optional): It is the device of the returned tensor. Default: None, which causes the device of obj to be used.
  5. requires_grad (bool, optional): Whether the returned tensor requires grad. Default: False, which causes the returned tensor not to require a gradient. If True, the returned tensor will require a gradient, and if obj is also a tensor with an autograd history, then the returned tensor will have the same history.


import torch
import numpy as np

# create a numpy array
arr = np.array([[1, 2], [3, 4]])

# convert it to a tensor using torch.asarray
tr = torch.asarray(arr)


[[1 2]
[3 4]]
<class 'numpy.ndarray'>

tensor([[1, 2],
[3, 4]])
<class 'torch.Tensor'>

That’s it!

Leave a Comment