PyTorch torch.from_numpy Function
Pytorch torch Reference Manual
torch.from_numpyis a function in PyTorch used to create a tensor from a NumPy array. The created tensor shares memory with the original NumPy array.
This is very useful in scenarios where both PyTorch and NumPy are needed 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: Creating 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)
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 will also change
print("NumPy array:", numpy_array)
print("PyTorch tensor:", tensor)
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 will also change
print("NumPy array:", numpy_array)
print("PyTorch tensor:", tensor)
The output is:
NumPy 数组: [100 2 3] PyTorch 张量: tensor([100, 2, 3])
Due to shared memory, modifying one will affect 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
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
Other Extensions