We use NumPy bridge to easily switch data between PyTorch and NumPy. This helps when you want to use both tools together.
0
0
NumPy bridge (from_numpy, numpy) in PyTorch
Introduction
You have data in NumPy and want to use PyTorch models.
You want to convert PyTorch tensors back to NumPy arrays for analysis or plotting.
You want to share data between PyTorch and other libraries that use NumPy.
You want to speed up data preparation by using NumPy functions before training in PyTorch.
Syntax
PyTorch
import torch import numpy as np # Convert NumPy array to PyTorch tensor tensor = torch.from_numpy(np_array) # Convert PyTorch tensor to NumPy array numpy_array = tensor.numpy()
from_numpy creates a tensor that shares memory with the NumPy array. Changing one changes the other.
numpy() returns a NumPy array that shares memory with the tensor. Changes affect both.
Examples
This converts a NumPy array to a PyTorch tensor.
PyTorch
import torch import numpy as np np_array = np.array([1, 2, 3]) tensor = torch.from_numpy(np_array) print(tensor)
This converts a PyTorch tensor to a NumPy array.
PyTorch
import torch tensor = torch.tensor([4, 5, 6]) np_array = tensor.numpy() print(np_array)
Changing the tensor also changes the original NumPy array because they share memory.
PyTorch
import torch import numpy as np np_array = np.array([7, 8, 9]) tensor = torch.from_numpy(np_array) tensor[0] = 10 print(np_array)
Sample Model
This program shows how to convert between NumPy arrays and PyTorch tensors. It also shows that they share memory, so changes in one affect the other.
PyTorch
import torch import numpy as np # Create a NumPy array np_array = np.array([1.0, 2.0, 3.0]) print(f"Original NumPy array: {np_array}") # Convert to PyTorch tensor tensor = torch.from_numpy(np_array) print(f"Converted to tensor: {tensor}") # Modify tensor tensor[1] = 20.0 print(f"Modified tensor: {tensor}") # Check NumPy array after tensor change print(f"NumPy array after tensor change: {np_array}") # Convert tensor back to NumPy np_array2 = tensor.numpy() print(f"NumPy array from tensor: {np_array2}")
OutputSuccess
Important Notes
Both conversions share memory, so be careful when modifying data.
PyTorch tensors created from NumPy arrays keep the same data type by default.
If you want a copy instead of shared memory, use tensor.clone() or np.copy().
Summary
Use torch.from_numpy() to convert NumPy arrays to PyTorch tensors.
Use tensor.numpy() to convert PyTorch tensors back to NumPy arrays.
Both share memory, so changes in one affect the other.