pytorch

How to Transform a PyTorch Variable into NumPy?

PyTorch” is a framework dedicated to the development of machine learning models and “NumPy” is meant for enhanced computation. They both utilize the interface of the “Python” programming language. Both of these have support for data analysis and deep learning applications however, they differ in their method of operation and preferences. PyTorch assorts data into “Tensors” whereas NumPy utilizes “arrays”.

In this blog, the attention will be on how to transform a Tensor in PyTorch to an array in NumPy.

Similarities Between PyTorch Tensors and NumPy Arrays

Similarities between tensors and arrays are due to their common backgrounds. Some of the important ones are as follows:

  • PyTorch and NumPy are both built around the “Python” interface.
  • Tensors and arrays are similar data structures because they can take the input of “multidimensional data”.
  • They can both store image data in a similar fashion i.e. multidimensional arrays or tensors dedicated to storing values for pixel brightness and color channels.
  • The “vector-based” approach to running operations is the same for both tensors and arrays. It allows them to sequentially follow any computation procedure.
  • PyTorch and NumPy have a broad spectrum of “mathematical operations” available to be carried out on the tensors and arrays respectively.
  • Lastly, NumPy arrays and PyTorch tensors can be “transformed” into each other as demonstrated later in this article.

Differences Between PyTorch Tensors and NumPy Arrays

The disparity between PyTorch and NumPy arises from each of their dedicated applications. Some key differences are listed below:

  • PyTorch is specialized in the development of machine learning models by its creator Facebook, now Meta. On the other hand, NumPy is more geared towards mathematical computation.
  • PyTorch has added the functionality of “GPUs” for faster processing and running multiple threads simultaneously. However, NumPy does not support GPUs right out of the box.
  • NumPy is itself a Python library whereas PyTorch is based on the “Torch” library.
  • PyTorch is based on the “tensors” data structure whereas NumPy has its “arrays”.

How to Transform a Tensor in PyTorch into an Array in NumPy?

PyTorch and NumPy have maintained their interoperability to allow programmers and data scientists to get the best of both worlds.

Follow the steps below to learn how to transform a PyTorch tensor into a NumPy array in Colab:

Step 1: Start a Colab Notebook

Go to the Colaboratory website and click on the “New Notebook” option to start a project:

Step 2: Import the Necessary Libraries

Install and import the “Torch” and “NumPy” libraries to give the project the functionality of both:

!pip install torch

import torch
import numpy as np

 

Step 3: Input PyTorch Tensor

Add the input of the PyTorch tensor to be transformed into a NumPy array:

PyTorch_2D_tensor = torch.tensor([
    [0, 3, 3, 6],
    [2, 9, 1, 9],
    [7, 4, 2, 9],
    [8, 4, 2, 1]])

print("PyTorch Tensor: \n", PyTorch_2D_tensor)
print("\n Shape:", PyTorch_2D_tensor.shape)

 

The above code works as follows:

  • Use the “torch.tensor()” method to input a 2-dimensional tensor as shown.
  • Input some random numbers by hand as done above or use the “randn” or “randint” methods.
  • Next, use the “print()” method to showcase the output.
  • Additionally, the “shape” method is used because it shows how many rows and columns are there in the tensor.
  • Moreover, the “\n” method is used to add line spacing in the output for a cleaner look.

The below output shows the generated tensor along with shape information:

Step 4: Transform Tensor to NumPy Array

In the last step, use the “numpy()” method to transform the tensor to an array:

NumPy_array = PyTorch_2D_tensor.numpy()
print("NumPy array: \n", NumPy_array)

 

The above code works as follows:

  • Use the “numpy()” method with the previously defined tensor variable and assign it to the “NumPy_array” variable.
  • Next, use the “print()” method to showcase the array in the output.

The below results shows that we have transformed the tensor to array successfully:

Note: You can access our Google Colab Notebook at this link.

Pro-Tip

If you are transforming a multidimensional tensor with a multitude of data values into an array, it is recommended to do it in batches for efficient processing. Furthermore, if not set by default, change the runtime settings to CPU because numpy arrays are not able to natively run on GPUs.

Success! We have just demonstrated how to transform a 2D tensor of PyTorch into a NumPy array.

Conclusion

To transform the Tensor to array, first, install Torch and NumPy libraries, input the tensor with the “torch.tensor()” method, and then use the “numpy()” method to transform a PyTorch variable into a NumPy array. This technique to interchange tensors and arrays is useful for developers looking to utilize the features of NumPy not available in PyTorch or vice versa. In this article, we have outlined the similarities and differences between Tensors and arrays as well as how to transform a PyTorch variable into NumPy.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.