Python PyTorch from_numpy()

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.