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

**data (array_like)**: Initial data for the tensor. It can be a list, tuple, NumPy ndarray, scalar, and other types.

**dtype (torch.dtype, optional)**: The desired data type of the returned tensor. Default: if None, infers data type from data.

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

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.