PyTorch torch.from_numpy function
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:
ndarray(numpy.ndarray): The input NumPy array.
Return Value:
torch.Tensor: Returns a tensor that shares memory with the NumPy array.
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
)
(
"NumPy array:"
)
(
numpy_array
)
(
"PyTorch tensor:"
)
(
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
(
"NumPy array:"
,
numpy_array
)
(
"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
)
(
"dtype:"
,
tensor.
dtype
)