Pytorch is a machine learning library that allows you to do projects based on computer vision and natural language processing. In this tutorial, I will show you how to convert PyTorch tensor to NumPy array and NumPy array to PyTorch tensor.

## Convert Pytorch Tensor to Numpy Array

In this section, You will learn how to create a PyTorch tensor and then convert it to NumPy array. Let’s import torch and create a tensor using it.

```
import torch
tensor_arr = torch.tensor([[10,20,30],[40,50,60],[70,80,90]])
tensor_arr
```

The above code is using the * torch.tensor() *method for generating tensor. There are two ways you can convert tensor to NumPy array.

### By detaching the tensor.

```
numpy_array= tensor_arr.cpu().detach().numpy()
numpy_array
```

**Output**

Here I am first detaching the tensor from the CPU and then using the * numpy() *method for NumPy conversion. The detach() creates a tensor that shares storage with a tensor that does not require grad. The above tensor created doesn’t have a gradient.

### Using Simple numpy() Method.

```
numpy_arr2 = tensor_arr.numpy()
numpy_arr2
```

*. It is because tensors that require_grad=True are recorded by PyTorch.*

**tensor.detach().numpy() method****Creation of tensor**

```
# cpu tensor with requires_grad=True
tensor_arr2 = torch.tensor([[1.,2,3],[4,5,6],[7,8,9]],requires_grad=True)
tensor_arr2
```

**Conversion to NumPy array**

```
numpy_arr3 = tensor_arr2.detach().numpy()
numpy_arr3
```

**Output**

## Convert Numpy Array to Pytorch Tensor

The above example was for converting PyTorch tensor to NumPy array. In this section, you will learn to convert a NumPy array to a tensor.

Let’s create a NumPy array. To create a NumPy array you have to use the * numpy.array()* method. Execute the following code.

```
numpy_array = np.array([[1,2,3],[4,5,6],[7,8,9]])
numpy_array
```

**Conversion of NumPy array to PyTorch using from_numpy() method**

There is a method in the Pytorch library for converting the NumPy array to PyTorch. It is * from_numpy().* Just pass the NumPy array into it to get the tensor.

```
tensor_arr = torch.from_numpy(numpy_array)
tensor_arr
```

**Output**

The above conversion is done using the CPU device. But if you want to get the tensor using GPU then you have to define the device for it. Below is the code for the conversion of the above NumPy array to tensor using the GPU.

```
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# check Cuda is available or not
tensor_with_gpu=torch.from_numpy(numpy_array).to(device)
tensor_with_gpu
```

**Output**

These are the examples for the conversion of tensor to NumPy array and vice-versa. Hope you have liked this tutorial. If you have any queries then you can contact us for more information.

#### Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.