How To Convert A Numpy Array To Torch Tensor?

This recipe helps you convert a numy array to torch tensor

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

This beginner-friendly PyTorch code will show you how to convert Numpy array to torch tensor using a simple PyTorch tensor example.

How To Convert Numpy Array To Torch Tensor?

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

  1. Using The torch.from_numpy() Function

This function takes a NumPy array as input and returns a PyTorch tensor that shares the same underlying data. Any changes made to the tensor will be reflected in the NumPy array and vice versa.

  1. Using The torch.tensor() Function 

This function can help you create a new PyTorch tensor from any Python iterable, including NumPy arrays. However, the torch.tensor() function will create a new copy of the NumPy array, meaning that any changes made to the tensor will not be reflected in the NumPy array and vice versa.

Steps Showing How To Convert NumPy Array To Tensor Torch

The following steps will show you how to convert a numpy array to a torch tensor 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

import numpy as np

Step 2 - Take A Sample NumPy Array

The next step is to take any sample numpy array.

array = np.array([55,66,77])

print("This is a Sample numpy array:",array, type(array))

The output of the above code is-

This is a Sample numpy array: [55 66 77] <class 'numpy.ndarray'>

Step 3 - Convert Numpy Array To Torch Tensor

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

torch = torch.from_numpy(array)

print("Converted numpy array to torch tensor:", torch, type(torch)

The output of the above code is-

Converted numpy array to torch tensor: tensor([55, 66, 77]) <class 'torch.Tensor'>

This will convert the Numpy array to a PyTorch tensor.

Convert Numpy Array To PyTorch Tensor With ProjectPro

This step-by-step PyTorch code example thoroughly explains converting Numpy arrays to PyTorch tensors. We have walked through the essential steps to seamlessly convert from one data format (numpy array) to another (torch tensor), 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

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

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.

Recommender System Machine Learning Project for Beginners-3
Content Based Recommender System Project - Building a Content-Based Product Recommender App with Streamlit

Learn How to Build PyTorch Neural Networks from Scratch
In this deep learning project, you will learn how to build PyTorch neural networks from scratch.

Build a Multi-Class Classification Model in Python on Saturn Cloud
In this machine learning classification project, you will build a multi-class classification model in Python on Saturn Cloud to predict the license status of a business.

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.

Learn to Build an End-to-End Machine Learning Pipeline - Part 1
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, addressing a major challenge in the logistics industry.

Build Deep Autoencoders Model for Anomaly Detection in Python
In this deep learning project , you will build and deploy a deep autoencoders model using Flask.

Classification Projects on Machine Learning for Beginners - 1
Classification ML Project for Beginners - A Hands-On Approach to Implementing Different Types of Classification Algorithms in Machine Learning for Predictive Modelling

Topic modelling using Kmeans clustering to group customer reviews
In this Kmeans clustering machine learning project, you will perform topic modelling in order to group customer reviews based on recurring patterns.

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.