from mxnet import np, npx
npx.set_np()A tensor is an n-dimensional array of numbers — the fundamental data structure for everything that follows in this book.
ndarray, but GPU-accelerated and differentiable.In this section: how to create, reshape, index, operate on, and share memory with tensors.
A single import wires up the framework’s tensor library:
Two attributes you’ll reach for constantly:
.numel() — the total number of elements.shape — the size along each axis (a tuple)reshape rearranges the same elements into a different shape — the total numel is preserved.
A 12-element vector becomes a 3\times 4 matrix. No data is copied; only the stride metadata changes.
Constant fills take a shape tuple — any rank, any size:
For exact control, pass a (nested) list literal — same row-major convention as NumPy:
Standard NumPy-style indexing:
X[-1] — the last rowX[1:3] — rows 1 and 2 (3 is exclusive)Assignment works the same way:
Most common math is applied elementwise — same shape in, same shape out.
cat glues tensors along an existing axis. Pick the axis with dim:
dim=0 → stack rows (more rows out)dim=1 → stack columns (wider matrix out)Comparison operators broadcast and return a boolean tensor of the same shape — useful for masking entries that satisfy a condition:
When tensors of different shapes meet, the smaller one is virtually expanded along missing dimensions — no data copy.
The rule: dimensions of size 1 stretch; everything else must match.
Y = Y + XEvery assignment of an arithmetic expression allocates a new tensor. Matters a lot when Y is gigabytes:
id(Y) == before is False: Y now points at a brand-new buffer.
Pre-allocate the output and write into it with Z[:] = ...:
Tensors and NumPy ndarrays convert cheaply — most frameworks share storage with NumPy when possible:
arange / zeros / ones / randn / tensor(list) — create..shape, .numel(), reshape — inspect / reorganize.[i, j], [a:b, c:d] — read and write slices.+ - * / **, cat, ==, sum — element-wise ops, joins, comparisons, reductions..numpy() / .item() — leave the tensor world.