Python / PyTorch Fundamentals Interview Questions
What is the difference between torch.tensor() and torch.Tensor() (capital T) for creating tensors?
This is a subtle but important PyTorch gotcha. torch.tensor() (lowercase, a function) infers dtype from the input data and copies it — the recommended way to create tensors from data. torch.Tensor() (uppercase, a class constructor) is an alias for torch.FloatTensor and behaves inconsistently depending on the argument type.
import torch
# ── torch.tensor() — RECOMMENDED, infers dtype, copies data
a = torch.tensor([1, 2, 3])
print(a.dtype) # torch.int64 — inferred from Python ints
b = torch.tensor([1.0, 2.0, 3.0])
print(b.dtype) # torch.float32 — inferred from Python floats
c = torch.tensor([1, 2, 3], dtype=torch.float32) # explicit override
print(c.dtype) # torch.float32
# ── torch.Tensor() — confusing, AVOID for creating tensors from data
d = torch.Tensor([1, 2, 3])
print(d.dtype) # torch.float32 — ALWAYS float32, ignores int input!
e = torch.Tensor(3, 4) # interprets ints as a SHAPE, not data!
print(e.shape) # torch.Size([3, 4]) — uninitialised memory, random values
# Common gotcha: these look similar but behave VERY differently
f1 = torch.tensor(3) # scalar tensor with value 3
f2 = torch.Tensor(3) # tensor of SHAPE (3,) with garbage/uninitialised values!
print(f1) # tensor(3)
print(f2) # tensor([4.6e-41, 0.0, 1.4e-45]) — random uninitialised memory!
# Recommended explicit constructors for empty/typed tensors:
g = torch.empty(3, 4) # uninitialised, explicit intent
h = torch.zeros(3, 4, dtype=torch.float32)
i = torch.ones(3, 4, dtype=torch.int64)Rule of thumb: always use lowercase torch.tensor() when creating a tensor from existing data (a list, NumPy array, or scalar). Use torch.zeros(), torch.ones(), torch.empty(), or torch.rand() when you want a new tensor of a given shape. Avoid torch.Tensor() entirely in new code.
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...
