We use NumPy bridge to easily switch data between PyTorch and NumPy. This helps when you want to use both tools together.
NumPy bridge (from_numpy, numpy) in 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.
import torch import numpy as np np_array = np.array([1, 2, 3]) tensor = torch.from_numpy(np_array) print(tensor)
import torch tensor = torch.tensor([4, 5, 6]) np_array = tensor.numpy() print(np_array)
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)
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.
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}")
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().
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.
Practice
torch.from_numpy() do in PyTorch?Solution
Step 1: Understand the function purpose
torch.from_numpy()is designed to take a NumPy array and create a PyTorch tensor from it.Step 2: Memory sharing behavior
The created tensor shares the same memory with the original NumPy array, so changes in one affect the other.Final Answer:
Converts a NumPy array into a PyTorch tensor sharing the same memory -> Option CQuick Check:
from_numpy() converts NumPy array to tensor [OK]
- Confusing from_numpy with tensor.numpy()
- Thinking it copies data instead of sharing memory
- Assuming it creates a tensor from a Python list
t back to a NumPy array?Solution
Step 1: Identify the method to convert tensor to NumPy
PyTorch tensors have a method callednumpy()that returns a NumPy array sharing the same data.Step 2: Check syntax correctness
The correct syntax is callingt.numpy()on the tensor object.Final Answer:
t.numpy() -> Option AQuick Check:
tensor.numpy() converts tensor to NumPy array [OK]
- Using numpy(t) which is invalid
- Confusing from_numpy with numpy()
- Using a non-existent method like to_numpy()
import torch import numpy as np np_array = np.array([1, 2, 3]) tensor = torch.from_numpy(np_array) np_array[0] = 10 print(tensor)
Solution
Step 1: Understand memory sharing between NumPy and tensor
The tensor created bytorch.from_numpy()shares memory with the NumPy array, so changes in the array affect the tensor.Step 2: Analyze the code change
Changingnp_array[0]to 10 updates the shared memory, so the tensor reflects this change.Final Answer:
tensor([10, 2, 3]) -> Option DQuick Check:
Shared memory means tensor updates with NumPy changes [OK]
- Assuming tensor is independent and unchanged
- Thinking tensor is immutable and throws error
- Confusing tensor.numpy() with from_numpy()
import torch import numpy as np np_array = np.array([1, 2, 3]) tensor = torch.from_numpy(np_array) tensor += 1 print(np_array)
Solution
Step 1: Understand memory sharing
Tensors fromtorch.from_numpy()share memory with NumPy arrays, so in-place operations like+=modify both.Step 2: Analyze the operation
tensor += 1performs in-place addition on the shared memory. No error occurs, andnp_arraybecomes [2, 3, 4].Final Answer:
No error; np_array will print [2, 3, 4] -> Option AQuick Check:
In-place ops on from_numpy tensors modify NumPy array [OK]
- Thinking it causes RuntimeError because tensor not writable
- Assuming tensor is independent copy
- Confusing with syntax error
arr = np.array([1, 2, 3]). You want to create a PyTorch tensor from it, modify the tensor without affecting the original array, and then convert the tensor back to a NumPy array. Which code snippet achieves this correctly?Solution
Step 1: Understand memory sharing and cloning
torch.from_numpy()shares memory with the NumPy array, so modifying the tensor changes the array. Usingtorch.tensor()creates a copy, so changes don't affect the original.Step 2: Check each option
tensor = torch.from_numpy(arr) tensor[0] = 10 new_arr = tensor.numpy() shares memory, so modifies arr.
tensor = torch.from_numpy(arr) tensor.clone() tensor[0] = 10 new_arr = tensor.numpy() calls clone() without assigning back to tensor, so tensor remains shared and modifies arr.
tensor = torch.tensor(arr) tensor[0] = 10 new_arr = tensor.numpy() creates an independent copy, safe.
tensor = torch.tensor(arr) arr[0] = 10 new_arr = tensor.numpy() modifies arr directly.Final Answer:
tensor = torch.tensor(arr) tensor[0] = 10 new_arr = tensor.numpy() -> Option BQuick Check:
Use torch.tensor() to avoid shared memory [OK]
- Using from_numpy and modifying tensor affects original array
- Calling clone() without reassigning the tensor
- Modifying original array instead of tensor
Ready to prove it?
Pass the test and this pattern moves unknown
