How To Convert A Torch Tensor To Numpy Array?

This easy-to-follow PyTorch code example helps you learn how to convert a torch tensor to numpy array.

Objective For ‘How To Convert Torch Tensor To Numpy Array?’

This step-by-step PyTorch code will show you how to convert PyTorch tensor to Numpy array using a simple PyTorch tensor example.

How To Convert Tensor Torch To Numpy Array?

There are two ways to convert a PyTorch tensor to a NumPy array-

  1. Using The .numpy() Method 

This will return a NumPy array with the same memory as the PyTorch tensor. Therefore, changes to the original tensor will affect the NumPy array and vice versa. In this PyTorch example, you will use the .numoy() method to convert torch tensor to numpy array.

  1. Using The np.array() Function 

This function can convert any Python object to a NumPy array, including PyTorch tensors. However, the resulting NumPy array will not share the same memory as the original PyTorch tensor. Therefore, changes to the original tensor will not affect the NumPy array and vice versa.

Steps Showing How To Convert Torch Tensor To NumPy Array

The following steps will show you how to convert a torch tensor to numpy array using the ‘.numpy()’ function.

Get Closer To Your Dream of Becoming a Data Scientist with Solved End-to-End PyTorch Projects

Step 1 - Import Library

First, you must import the required libraries.

import torch

Step 2 - Take A Sample Tensor

The next step is to take any sample tensor.

tensor = torch.tensor([3,4,5,6])

print("This is a Sample tensor with dtype:", tensor, type(tensor))

The output of the above code is-

This is a Sample tensor with dtype: tensor([3, 4, 5, 6]) <class 'torch.Tensor'>

Step 3 - Convert The Torch Tensor To Array

The final step is to convert the sample tensor to a numpy array using the .numpy() method.

numpy_array = tensor.numpy()

print("Convert the tensor into numpy array:",numpy_array, type(numpy_array))

The output of the above code is-

Convert the tensor from torch to numpy array: [3 4 5 6] <class 'numpy.ndarray'>

This will convert the torch tensor to array.

Convert PyTorch Tensor To Numpy Array With ProjectPro

This step-by-step PyTorch code example thoroughly explains converting Torch tensors to NumPy arrays in PyTorch. We have walked through the essential steps to seamlessly convert from one data format (tensor) to another (numpy array), allowing efficient data handling and integration with other libraries and tools. Furthermore, if you want to expand your proficiency in PyTorch and apply it to real-world data science and machine learning solutions, you must explore the ProjectPro platform. By engaging with over 270 end-to-end solved projects in the ProjectPro repository, you can gain the skills and expertise needed to excel in data science and machine learning.

What Users are saying..

profile image

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.

MLOps AWS Project on Topic Modeling using Gunicorn Flask
In this project we will see the end-to-end machine learning development process to design, build and manage reproducible, testable, and evolvable machine learning models by using AWS

End-to-End ML Model Monitoring using Airflow and Docker
In this MLOps Project, you will learn to build an end to end pipeline to monitor any changes in the predictive power of model or degradation of data.

NLP Project for Beginners on Text Processing and Classification
This Project Explains the Basic Text Preprocessing and How to Build a Classification Model in Python

Build an Image Segmentation Model using Amazon SageMaker
In this Machine Learning Project, you will learn to implement the UNet Architecture and build an Image Segmentation Model using Amazon SageMaker

PyTorch Project to Build a GAN Model on MNIST Dataset
In this deep learning project, you will learn how to build a GAN Model on MNIST Dataset for generating new images of handwritten digits.

Digit Recognition using CNN for MNIST Dataset in Python
In this deep learning project, you will build a convolutional neural network using MNIST dataset for handwritten digit recognition.

Insurance Pricing Forecast Using XGBoost Regressor
In this project, we are going to talk about insurance forecast by using linear and xgboost regression techniques.

Build a Collaborative Filtering Recommender System in Python
Use the Amazon Reviews/Ratings dataset of 2 Million records to build a recommender system using memory-based collaborative filtering in Python.

AWS MLOps Project to Deploy Multiple Linear Regression Model
Build and Deploy a Multiple Linear Regression Model in Python on AWS