Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python PyTorch from_numpy()

  • Last Updated : 22 Apr, 2020

PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.

The function torch.from_numpy() provides support for the conversion of a numpy array into a tensor in PyTorch. It expects the input as a numpy array (numpy.ndarray). The output type is tensor. The returned tensor and ndarray share the same memory. The returned tensor is not resizable.

It currently accepts ndarray with dtypes of numpy.float64, numpy.float32, numpy.float16, numpy.int64, numpy.int32, numpy.int16, numpy.int8, numpy.uint8, and numpy.bool.

Syntax: torch.sinh(ndarray)

Parameters:
ndarray: Input Numpy array (numpy.ndarray)

Return type: A tensor with the same type as that of x.

Code #1:




# Importing the PyTorch library
import torch
import numpy
  
# A numpy array of size 6
a = numpy.array([1.0, -0.5, 3.4, -2.1, 0.0, -6.5])
print(a)
  
# Applying the from_numpy function and
# storing the resulting tensor in 't'
t = torch.from_numpy(a)
print(t)

Output:

[ 1.  -0.5  3.4 -2.1  0.  -6.5]
tensor([ 1.0000, -0.5000,  3.4000, -2.1000,  0.0000, -6.5000],
       dtype=torch.float64)

 

Modifications to the tensor will be reflected in the ndarray and vice versa.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!