Creating tensors and reading their shape, dtype, and device.
A PyTorch is NumPy's ndarray with two extra
superpowers: it can live on a GPU, and it can remember the operations that
built it so can flow backward through them via
(Lesson 3). If you already know NumPy, most of
this will feel familiar: the API is deliberately close.
importtorch
a = torch.tensor([1.0, 2.0, 3.0])
print(a.shape, a.dtype, a.device)
print(torch.zeros(2, 3))
print(torch.arange(0, 10, 2))
print(torch.rand(2, 2)) # uniform [0, 1)print(torch.randn(2, 2)) # standard normal
⚠️ Watch out: torch.rand and torch.randn are NOT interchangeable, despite the near-identical names. rand(shape) is UNIFORM over [0, 1): every value equally likely, always non-negative. randn(shape) is standard NORMAL (Gaussian, mean 0, std 1): can be negative, most values cluster near 0. Mixing them up is a very easy, very common mistake.
Call
Makes
Example
torch.tensor(data)
a tensor from existing data (list, NumPy array, …)
torch.tensor([1, 2, 3]) → tensor([1, 2, 3])
torch.zeros(shape) / torch.ones(shape)
filled with 0s / 1s
torch.zeros(3) → tensor([0., 0., 0.])
torch.arange(start, stop, step)
like NumPy's arange
torch.arange(0, 6, 2) → tensor([0, 2, 4])
torch.eye(n)
n×n identity matrix
torch.eye(2) → tensor([[1., 0.], [0., 1.]])
torch.rand(shape)
uniform random values in [0, 1)
torch.rand(2) → e.g. tensor([0.42, 0.91]), always ≥ 0
torch.randn(shape)
normal/Gaussian random values (mean 0, std 1)
torch.randn(2) → e.g. tensor([-0.3, 1.2]), can be negative
x.float(), x.long(), x.to(torch.float32)
dtype casts
torch.tensor([1, 2]).float() → tensor([1., 2.])
💡 Tip: torch.manual_seed(0) makes random tensors reproducible, which is essential when you need the same 'random' result on every run (like in these lessons' examples).