x = torch.arange(12, dtype=torch.float32)
xDive into Deep Learning · §1.1
Storing & transforming data with tensors
The n-dimensional arrays that every model in this book is built on.
Motivation
ndarray.Rank = number of axes; shape = size per axis.
01
Getting Started
creating & inspecting tensors
Getting Started
arange(n) builds a 1-D tensor of evenly spaced values:
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.])
torch.Size([12])
numel() → total elements. shape → size along each axis. We ask for float32 because nearly all neural-net math is in floating point.
Getting Started
For weight init, randn draws from \mathcal{N}(0, 1):
tensor([[ 0.0942, 1.5862, -0.2353, 0.6500],
[ 0.4769, -1.1740, 0.5365, -0.1956],
[-1.5313, -0.3069, 0.2684, -1.1082]])
Also zeros, ones, full(shape, value), eye(n). Random values break symmetry when initializing network weights; lists let you type a tensor by hand.
Getting Started
02
Indexing & Slicing
reading & writing elements, rows, ranges
Indexing & Slicing
Indexing & Slicing
03
Operations
elementwise math, joins, comparisons, broadcasting
Operations
The operators + - * / ** act elementwise on matching shapes:
(tensor([ 3., 4., 6., 10.]),
tensor([-1., 0., 2., 6.]),
tensor([ 2., 4., 8., 16.]),
tensor([0.5000, 1.0000, 2.0000, 4.0000]),
tensor([ 1., 4., 16., 64.]))
Any scalar→scalar map (exp, sin, log) extends to a whole tensor.
Operations
Operations
Comparisons return a boolean tensor.
A ready-made mask:
tensor([[False, True, False, True],
[False, False, False, False],
[False, False, False, False]])
==, <, > build masks; sum, mean, max reduce axes; add dim= to reduce one selected axis.
Operations · the exception
Size-1 axes are expanded virtually:
a 3\times1 plus a 1\times2 gives a 3\times2:
tensor([[0, 1],
[1, 2],
[2, 3]])
An axis of size 1 can expand to match the other tensor without a copy.
Compatible only if each axis is equal or 1.
Operations · the exception
Line up (3, 2) and (2, 3) from the right, pairing 2 with 3 and 3 with 2: no pair matches, neither member is 1, so the framework raises rather than guessing:
The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1
Broadcasting aligns shapes from the right; each axis pair must be equal or 1.
04
Memory & Interop
in-place updates and leaving the tensor world
Y = Y + XPerformance
In eager execution, Y = Y + X typically allocates a new tensor, which is costly when Y is large and updated frequently:
False
id(Y) changed: Y is now bound to a new tensor object.
Performance
Interop
Wrap-up
arange, zeros, ones, randn, tensor([…])..shape, .numel(), reshape.cat.X[:] = …, +=), or in JAX via jit buffer reuse..item() for scalars.