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.
More Related questions...