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

The object can be one of the following:

- a tensor

- a NumPy array or a NumPy scalar

- a DLPack capsule

- an object that implements Python’s buffer protocol

- a scalar

- a sequence of scalars

**Syntax**

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

**Parameters**

**obj (object):**It is a tensor, NumPy array, DLPack Capsule object that implements Python’s buffer protocol, scalar, or sequence of scalars**dtype (torch.dtype, optional)**: The data type of the returned tensor. Default: None.

**copy (bool, optional)**: It controls whether the returned tensor shares memory with obj. Default: None.

**device (torch.device, optional)**: It is the device of the returned tensor. Default: None, which causes the device of obj to be used.

**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!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.