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 |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
