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

Syntax

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

Parameters

  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.

Example

import torch
import numpy as np

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

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

Output

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

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

That’s it!

Leave a Comment