Python / PyTorch Fundamentals Interview Questions
What is a PyTorch tensor and how does it differ from a NumPy array?
A tensor is PyTorch's core data structure — an n-dimensional array similar to NumPy's ndarray, but with two critical extra capabilities: it can live on a GPU for accelerated computation, and it supports automatic differentiation (autograd) for computing gradients during backpropagation.
import torch import numpy as np # Creating tensors t1 = torch.tensor([1.0, 2.0, 3.0]) # from Python list t2 = torch.zeros(3, 4) # 3Ã4 zeros t3 = torch.ones(2, 3) # 2Ã3 ones t4 = torch.rand(2, 3) # uniform random [0,1) t5 = torch.randn(2, 3) # standard normal t6 = torch.arange(0, 10, 2) # [0, 2, 4, 6, 8] t7 = torch.linspace(0, 1, 5) # 5 evenly spaced pts # Shape, dtype, device print(t2.shape) # torch.Size([3, 4]) print(t1.dtype) # torch.float32 print(t1.device) # cpu # NumPy â PyTorch bridge (shares memory on CPU!) np_array = np.array([1.0, 2.0, 3.0]) torch_from_np = torch.from_numpy(np_array) # shares memory np_from_torch = t1.numpy() # shares memory np_array[0] = 99 print(torch_from_np[0]) # tensor(99.) â memory is shared!
| Feature | PyTorch Tensor | NumPy ndarray |
|---|---|---|
| GPU support | Yes — .to('cuda') | No |
| Autograd | Yes — requires_grad=True | No |
| Memory sharing | Yes (CPU tensors) | Yes (via from_numpy) |
| Default dtype | float32 | float64 |
| Broadcasting | Yes (same rules) | Yes |
More Related questions...