Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.from_numpy function

PyTorch torch.from_numpy function


PyTorch torch reference manual PyTorch torch reference manual

torch.from_numpy A function in PyTorch for creating a tensor from a NumPy array. The created tensor shares memory with the original NumPy array.

This is very useful in scenarios that require using both PyTorch and NumPy for data processing.

Function definition

torch.from_numpy(ndarray)

Parameters:

Return Value:


Usage examples

Example 1: Create a tensor from a NumPy array

Example

import

torch

import

numpy

as

np

Create a NumPy array

numpy_array

=

np.

array

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

)

Convert to a PyTorch tensor

tensor

=

torch.

from_numpy

(

numpy_array

)

print

(

"NumPy array:"

)

print

(

numpy_array

)

print

(

"PyTorch tensor:"

)

print

(

tensor

)

The output is:

NumPy 数组:

[[1 2 3]

 [4 5 6]]

PyTorch 张量:

tensor([[1, 2, 3],

        [4, 5, 6]])

Example 2: Memory sharing

Example

import

torch

import

numpy

as

np

Create a NumPy array

numpy_array

=

np.

array

(

[

1

,

2

,

3

]

)

Convert to a PyTorch tensor

tensor

=

torch.

from_numpy

(

numpy_array

)

Modify the tensor

tensor

[

0

]

=

100

The NumPy array also changes

print

(

"NumPy array:"

,

numpy_array

)

print

(

"PyTorch tensor:"

,

tensor

)

The output is:

NumPy 数组: [100   2   3]

PyTorch 张量: tensor([100,   2,   3])

Because memory is shared, modifying one affects the other.

Example 3: Data type conversion

Example

import

torch

import

numpy

as

np

NumPy creates int64 by default

numpy_array

=

np.

array

(

[

1

,

2

,

3

]

)

tensor

=

torch.

from_numpy

(

numpy_array

)

print

(

"dtype:"

,

tensor.

dtype

)

 

torch.int64


PyTorch torch reference manual PyTorch torch reference manual