Tensors, Axes, and Contractions
Extend matrix shape reasoning to arrays with any number of axes. Name axis meaning, distinguish tensor rank from matrix rank, compare dot and outer products, and track which indices remain or are summed away in a contraction.
A matrix has two axes, but many collections of data need more. A color image may have height, width, and channel axes. A batch of token representations may have batch, position, and feature axes. Such multi-axis arrays are commonly called tensors in numerical computing and machine learning. Their shapes become useful only when the meaning of every axis is known.
From Scalars to Multi-axis Arrays
The following objects form a useful progression:
| Object | Number of axes | Example shape | Possible axis meanings |
|---|---|---|---|
| Scalar | 0 | one value | |
| Vector | 1 | feature | |
| Matrix | 2 | example, feature | |
| Three-axis tensor | 3 | example, position, feature | |
| Four-axis tensor | 4 | example, height, width, channel |
In this lesson, tensor rank means the number of axes. This usage differs from matrix rank, which measures the number of independent directions in a matrix and is studied later. A three-axis tensor has tensor rank three whether or not its entries contain redundant information.
The word tensor also has a more precise meaning in multilinear algebra and geometry. Numerical libraries often use it more broadly for a multi-axis array. That computational meaning is sufficient for the shape reasoning developed here.
Exercise: Read a tensor shape completely
A tensor has shape with axes . Which statement is correct?
Select one choice, then check.
HintCount axes before reading their lengths
The shape tuple contains three entries. Then attach batch, position, and feature meanings in that order.
SolutionDistinguish axis count from axis length
The shape contains three axes, so has tensor rank three in the computational sense. Axis selects one of 32 examples, axis selects one of 128 positions in that example, and axis selects one of 768 features at that position. The number is an axis length, not a rank.
Indices Identify Positions Along Named Axes
If:
then an entry can be written . The indices have separate roles:
- selects an example from the batch;
- selects a position within that example;
- selects a feature at that position.
Fixing some indices produces a lower-dimensional slice. For example, is the matrix for one example, while is the length- feature vector at one position. The colon notation means “keep every index along this axis.”
Axis order is part of the representation. Reordering to preserves the entries but changes which index position selects the batch. It must be represented by an explicit permutation or transpose operation; it is not merely a new verbal description of the same shape.
Outer Products Keep Both Input Axes
The dot product of two equal-length vectors contracts their shared coordinate index and produces a scalar:
An outer product performs the pairwise multiplications without summing:
If and , then:
For example:
The output retains one axis from each input. This is the opposite of summing the shared coordinate pairs into one value.
Exercise: Compare dot and outer products
Let . What are the output shapes of and , respectively?
Select one choice, then check.
HintTrack the indices
The dot product contains . The outer product contains an unsummed pair .
SolutionIdentify contracted and free indices
In the dot product, the shared index is summed away, leaving no free index and therefore a scalar. In the outer product, and remain free, giving one row and one column axis of length four. Its shape is .
Contraction Sums Over Matched Axes
A tensor contraction multiplies entries and sums over one or more matched indices. Matrix multiplication is the familiar example:
The index is a contracted index: it occurs in both factors and is summed away. The indices and are free indices: they remain in the output and determine its axes.
This language extends to higher-rank arrays. Suppose a batch of position-wise feature vectors has shape:
and a weight matrix has shape:
Applying to the feature vector at every batch and position gives:
Read this as: “for example , position , and output feature , multiply corresponding input features and weights across every input-feature index , then add those products.”
The input-feature index is contracted. The batch index , position index , and output-feature index remain. Therefore:
Shape reasoning can be performed without expanding the entries:
Exercise: Find contracted and remaining axes
Let have shape with axes , and let have shape . For , which description is correct?
Select one choice, then check.
HintRead the index formula
The summation is over . The output is labelled by , , and .
SolutionRemove the summed index
The index selects the 64 input features in both and , so it is multiplied and summed away. The free indices have lengths , , and . Hence:
Every example and position remains, but its length- input feature vector is replaced by a length- output feature vector.
Broadcasting and Contraction Do Different Work
Broadcasting reuses values along compatible axes; it does not sum an axis away. Contraction multiplies values and explicitly sums over matched axes.
For example, if has shape and has shape , then broadcasts the same length- vector across every batch and position. The output still has shape . By contrast, a dot product between the final axis of and a length- vector contracts that axis and produces shape .
Code can sometimes run even when the intended operation is wrong. Matching sizes are therefore only the first check. The operation must also match the meaning of the axes.
Verify Shapes and Values in NumPy
NumPy applies matrix multiplication to the final two axes while carrying earlier batch-like axes into the result:
Contract the feature axis of a three-axis tensor
Change the axis lengths or entries and compare the predicted and computed output shapes.
Ready to run.
The function np.einsum is named after the Einstein summation convention,
a compact notation in which a repeated index is understood to be summed. Its
first argument is a string that describes the input and output indices:
"blk,kj->blj"
│ │ │
X W Y
The part before -> describes the inputs in the same order as the arrays
passed to the function:
blkassigns indices , , and to the three axes ofX;kjassigns indices and to the two axes ofW.
The part after -> lists the output indices and their order. Here it keeps
b, l, and j, producing an array with axes . The
index k occurs in both inputs but not in the output, so einsum multiplies
matching entries and sums over that axis:
The letters have no built-in meaning to NumPy; b, l, and k are useful
because we choose them to suggest batch, position, and feature. What matters to
einsum is where each label appears. This notation can express many
contractions and axis rearrangements, but ordinary @ is clearer for standard
matrix multiplication. Use einsum when an explicit index pattern makes a
higher-rank operation easier to verify, not merely because it is shorter.
A Reliable Shape-reading Method
For any tensor expression:
- Name every input axis and write its length.
- Mark axes that must match.
- Identify indices that are summed away.
- List the free indices in output order.
- Check that the resulting axes still have the intended meaning.
This method applies to ordinary matrix products, batched neural network layers, image operations, and the attention calculations studied later. The chapter review now collects these tensor rules with the earlier matrix operations.