Tensors from torch.from_numpy() share memory with NumPy arrays, so in-place operations like += modify both.
Step 2: Analyze the operation
tensor += 1 performs in-place addition on the shared memory. No error occurs, and np_array becomes [2, 3, 4].
Final Answer:
No error; np_array will print [2, 3, 4] -> Option A
Quick Check:
In-place ops on from_numpy tensors modify NumPy array [OK]
Hint: In-place ops on from_numpy tensors modify NumPy array [OK]
Common Mistakes:
Thinking it causes RuntimeError because tensor not writable
Assuming tensor is independent copy
Confusing with syntax error
5. You have a NumPy array 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?
hard
A. tensor = torch.from_numpy(arr)
tensor[0] = 10
new_arr = tensor.numpy()
B. tensor = torch.tensor(arr)
tensor[0] = 10
new_arr = tensor.numpy()
D. tensor = torch.tensor(arr)
arr[0] = 10
new_arr = tensor.numpy()
Solution
Step 1: Understand memory sharing and cloning
torch.from_numpy() shares memory with the NumPy array, so modifying the tensor changes the array. Using torch.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.