0
0
PyTorchml~20 mins

NumPy bridge (from_numpy, numpy) in PyTorch - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
NumPy Bridge Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of PyTorch tensor from NumPy array modification
What is the output of the following code snippet?
PyTorch
import numpy as np
import torch
np_array = np.array([1, 2, 3])
torch_tensor = torch.from_numpy(np_array)
np_array[0] = 10
print(torch_tensor)
Atensor([10, 2, 3])
BRaises RuntimeError
Ctensor([0, 2, 3])
Dtensor([1, 2, 3])
Attempts:
2 left
💡 Hint
Remember that torch.from_numpy shares memory with the NumPy array.
Predict Output
intermediate
2:00remaining
Effect of modifying PyTorch tensor on original NumPy array
What will be the output of the following code?
PyTorch
import numpy as np
import torch
np_array = np.array([4, 5, 6])
torch_tensor = torch.from_numpy(np_array)
torch_tensor[1] = 50
print(np_array)
A[0 50 0]
B[4 5 6]
C[ 4 50 6]
DRaises TypeError
Attempts:
2 left
💡 Hint
Think about whether the tensor and array share the same data.
Model Choice
advanced
2:00remaining
Choosing correct method to convert PyTorch tensor to NumPy array
Which method correctly converts a PyTorch tensor to a NumPy array without sharing memory?
Atensor.detach().numpy()
Btensor.clone().numpy()
Ctensor.numpy()
Dtensor.to_numpy()
Attempts:
2 left
💡 Hint
Consider how to avoid shared memory when converting.
Metrics
advanced
2:00remaining
Understanding tensor and NumPy array memory sharing impact on metrics
If you modify a PyTorch tensor created from a NumPy array using torch.from_numpy, how does it affect the calculation of the mean of the original NumPy array?
AThe mean changes because the NumPy array data changes with tensor modification.
BThe mean calculation raises an error due to shared memory.
CThe mean remains the same because tensors and arrays are independent.
DThe mean changes only if tensor requires_grad is True.
Attempts:
2 left
💡 Hint
Think about how shared memory affects data values.
🔧 Debug
expert
2:00remaining
Debugging error when converting CUDA tensor to NumPy array
What error occurs when running this code and why? import torch t = torch.tensor([1, 2, 3]).cuda() np_array = t.numpy()
ARuntimeError: Can't call numpy() on Tensor that requires grad and is on GPU
BAttributeError: 'Tensor' object has no attribute 'numpy'
CTypeError: Cannot convert CUDA tensor to NumPy array directly
DRuntimeError: Can't call numpy() on a CUDA tensor. Move it to CPU first.
Attempts:
2 left
💡 Hint
Consider where the tensor is located (CPU or GPU) when calling numpy().