Matrices as Linear Maps

Dive into Deep Learning · §33.2

Matrices as Linear Maps
column geometry · composition & einsum · rank–nullity · invertibility · determinants & volume scaling

When Does a Linear Layer Destroy Information?

Motivation

  • From Rows to Columns: Reading \mathbf{A}\mathbf{x} by rows shows m hyperplane tests, while reading by columns shows where the input coordinate axes land.
  • Dimension Bottlenecks: A 256 \times 784 Fashion-MNIST layer outputs fewer numbers than it takes in, collapsing at least 784 - 256 = 528 directions to zero.
  • Invertible vs. Singular: Running matrix \mathbf{A} = \left(\begin{smallmatrix}1&2\\-1&3\end{smallmatrix}\right) is reversible, whereas \mathbf{B} = \left(\begin{smallmatrix}2&1\\4&2\end{smallmatrix}\right) merges (1, 1) and (0, 3) onto (3, 6).

Columns Are the Images of the Coordinate Axes

Column Geometry

  • Action on Basis Vectors: Writing \mathbf{x} = x\mathbf{e}_1 + y\mathbf{e}_2 shows that \mathbf{A}\mathbf{x} is a weighted combination of the columns of \mathbf{A}: \mathbf{A}\mathbf{x} = x\,\mathbf{A}\mathbf{e}_1 + y\,\mathbf{A}\mathbf{e}_2
  • Running Matrix \mathbf{A}: Column 1 is \mathbf{A}\mathbf{e}_1 = (1, -1) and Column 2 is \mathbf{A}\mathbf{e}_2 = (2, 3), so \mathbf{v} = (2, -1) maps to 2(1, -1) - (2, 3) = (0, -5).
  • Grid Preservation: Because \mathbf{A}(\alpha\mathbf{x} + \beta\mathbf{y}) = \alpha\mathbf{A}\mathbf{x} + \beta\mathbf{A}\mathbf{y}, lines remain lines, the origin stays fixed (\mathbf{A}\mathbf{0} = \mathbf{0}), and the unit square maps to a parallelogram.

Six Geometric Actions on the Unit Square

Linear Map Gallery

  • Full-Rank vs. Rank-Deficient Maps: Scaling, rotation \mathbf{R}_{90} = \left(\begin{smallmatrix}0&-1\\1&0\end{smallmatrix}\right), shear \mathbf{T} = \left(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\right), and reflection map the unit square to a 2D parallelogram, whereas projection (e) and dependent columns (f) squash the entire plane onto a 1D line.
  • Affine Layers (\mathbf{W}\mathbf{x} + \mathbf{b}): A nonzero bias translation moves the origin (\mathbf{0} \mapsto \mathbf{b}), making an affine layer a linear map followed by a shift.

Matrix Multiplication Is Map Composition

Composition

  • Right-to-Left Composition: Applying \mathbf{B} first and \mathbf{A} second to \mathbf{v} equals applying the product \mathbf{A}\mathbf{B}, whose j-th column is \mathbf{A}\mathbf{b}_j: \bigl(\mathbf{A}(\mathbf{B}\mathbf{v})\bigr)_i = \sum_k \Bigl(\sum_j a_{ij} b_{jk}\Bigr) v_k = \bigl((\mathbf{A}\mathbf{B})\mathbf{v}\bigr)_i
  • Order Matters (\mathbf{R}_{90}\mathbf{T} \neq \mathbf{T}\mathbf{R}_{90}): Shearing then rotating sends \mathbf{e}_1 \mapsto (0, 1), whereas rotating then shearing sends \mathbf{e}_1 \mapsto (1, 1).
  • Associativity: (\mathbf{A}\mathbf{B})\mathbf{C} = \mathbf{A}(\mathbf{B}\mathbf{C}) holds automatically because function composition is associative.

Orthogonal Matrices Preserve Lengths and Angles

Rigid Motions

  • Orthonormal Columns (\mathbf{Q}^\top\mathbf{Q} = \mathbf{I}): Square \mathbf{Q} preserves dot products (\mathbf{Q}\mathbf{x})\cdot(\mathbf{Q}\mathbf{y}) = \mathbf{x}^\top\mathbf{Q}^\top\mathbf{Q}\mathbf{y} = \mathbf{x}\cdot\mathbf{y}, lengths, and angles.
  • Two-Sided Inverse (\mathbf{Q}^{-1} = \mathbf{Q}^\top): In \mathbb{R}^2, only rotations \mathbf{R}_\phi and reflections are orthogonal.
  • Equal Lengths Are Essential: \operatorname{diag}(1, 10) has perpendicular columns but bends 90^\circ into 169^\circ.

Einstein Summation Unifies Tensor Contractions

Index Notation

  • One Rule for Every Product: Multiply entries and sum over indices omitted after ->.
  • Cyclic Trace Invariance: \operatorname{tr}(\mathbf{A}\mathbf{B}) = \sum_{i,j} a_{ij}b_{ji} = \operatorname{tr}(\mathbf{B}\mathbf{A}), so \operatorname{tr}(\mathbf{V}\mathbf{A}\mathbf{V}^{-1}) = \operatorname{tr}(\mathbf{A}).
A = np.array([[1.0, 2.0], [-1.0, 3.0]])    # the running matrix
v = np.array([2.0, -1.0])
(np.einsum('i,i->', v, v),        # dot product: v.v
 np.einsum('ij,j->i', A, v),      # matrix-vector product: Av
 np.einsum('ij,jk->ik', R90, S),  # matrix product: R90 S
 np.einsum('ii->', A))            # trace: tr(A)
(np.float64(5.0),
 array([ 0., -5.]),
 array([[ 0., -1.],
        [ 1.,  1.]]),
 np.float64(4.0))

Multi-Head Attention Contractions With einsum

Index Notation in Practice

  • Named Kept vs. Summed Axes: 'bhij,bhtj->bhit' keeps batch b, head h, query i, key t, and sums feature width j.
  • Contraction Order Pitfall: Evaluating \mathbf{A}(\mathbf{B}\mathbf{v}) takes 2n^2 ops vs. n^3 for (\mathbf{A}\mathbf{B})\mathbf{v}.
rng = np.random.default_rng()
queries = rng.standard_normal((2, 3, 4, 8))   # (batch, heads, queries, width)
keys = rng.standard_normal((2, 3, 5, 8))      # (batch, heads, keys, width)
scores = np.einsum('bhij,bhtj->bhit', queries, keys)
(scores.shape, np.allclose(scores, queries @ keys.swapaxes(-1, -2)),
 scores.size * queries.shape[-1])             # multiply-adds
((2, 3, 4, 5), True, 960)

Column Space and Null Space of a Matrix

Fundamental Subspaces

  • Column Space (\operatorname{col}\mathbf{A} \subseteq \mathbb{R}^m): The span of the columns of \mathbf{A}, which is the exact set of reachable outputs \{\mathbf{A}\mathbf{x} : \mathbf{x} \in \mathbb{R}^n\}.
  • Null Space / Kernel (\ker\mathbf{A} \subseteq \mathbb{R}^n): The subspace of inputs crushed to zero, \{\mathbf{x} \in \mathbb{R}^n : \mathbf{A}\mathbf{x} = \mathbf{0}\}, consisting of all vectors orthogonal to every row of \mathbf{A}.
  • Singular Example \mathbf{B} = \left(\begin{smallmatrix}2&1\\4&2\end{smallmatrix}\right): Since \mathbf{b}_1 = 2\mathbf{b}_2, \operatorname{col}\mathbf{B} is the line y = 2x, and \ker\mathbf{B} is the line through (1, -2): inputs (1, 1) and (0, 3) differ by (1, -2) and collide at (3, 6).

The Rank–Nullity Theorem: Dimension Conservation

Rank and Dimension

  • Dimension Conservation: For every \mathbf{A} \in \mathbb{R}^{m \times n}, \operatorname{rank}\mathbf{A} + \dim\ker\mathbf{A} = n.
  • Proof by Basis Extension: Extending a basis \mathbf{w}_1, \ldots, \mathbf{w}_k of \ker\mathbf{A} with \mathbf{u}_1, \ldots, \mathbf{u}_{n-k} yields independent images \mathbf{A}\mathbf{u}_i spanning \operatorname{col}\mathbf{A}.
  • Bottleneck Layers: A 256 \times 784 layer has \operatorname{rank}\mathbf{A} \le 256, forcing \dim\ker\mathbf{A} \ge 528.

Row Rank Equals Column Rank & Bottleneck Factors

Rank and Bottlenecks

  • Rank-r Factorization (\mathbf{A} = \mathbf{G}\mathbf{H}): \mathbf{G} \in \mathbb{R}^{m \times r} holds a column-space basis and \mathbf{H} \in \mathbb{R}^{r \times n} holds row-space basis coefficients, proving row rank equals column rank.
  • Low-Rank Storage: \mathbf{G}\mathbf{H} stores r(m+n) numbers instead of mn.
B = np.array([[2.0, 1.0], [4.0, 2.0]])
C = np.array([[1, 3, 0, -1, 0], [-1, 0, 1, 1, -1],
              [0, 3, 1, 0, -1], [2, 3, -1, -2, 1]], dtype=float)
Z = np.array([[3, -1, 3, 0, 0], [1, 0, 0, 1, 0],
              [0, 0, 1, 0, 1]], dtype=float).T   # candidate null vectors
rank_C, rank_Z = np.linalg.matrix_rank(C), np.linalg.matrix_rank(Z)
np.linalg.matrix_rank(B), rank_C, np.abs(C @ Z).max(), rank_Z, rank_C + rank_Z
(np.int64(1), np.int64(2), np.float64(0.0), np.int64(3), np.int64(5))

Matrix Inverses and the 2×2 Explicit Formula

Invertibility

  • Two-Sided Inverse (\mathbf{A}^{-1}\mathbf{A} = \mathbf{A}\mathbf{A}^{-1} = \mathbf{I}): Uniquely recovers inputs via \mathbf{x} = \mathbf{A}^{-1}(\mathbf{A}\mathbf{x}).
  • Explicit 2 \times 2 Rule: When ps - qr \neq 0, \mathbf{A}^{-1} = \frac{1}{ps - qr}\left(\begin{smallmatrix}s & -q \\ -r & p\end{smallmatrix}\right).
  • Running Matrix \mathbf{A}: ps - qr = 5 gives \mathbf{A}^{-1} = \frac{1}{5}\left(\begin{smallmatrix}3&-2\\1&1\end{smallmatrix}\right), mapping (0, -5) \mapsto (2, -1).

The Invertible Matrix Theorem for Square Maps

Invertibility

For an n \times n square matrix \mathbf{A}, being one-to-one and being onto \mathbb{R}^n are equivalent, tying our subspace conditions together:

Proposition (Invertible Matrices). For an n \times n matrix \mathbf{A}, the following are equivalent: (i) \mathbf{A} is invertible; (ii) the columns of \mathbf{A} are linearly independent; (iii) \ker\mathbf{A} = \{\mathbf{0}\}; (iv) \operatorname{rank}\mathbf{A} = n.

  • Constructing \mathbf{A}^{-1} Column by Column: When \operatorname{rank}\mathbf{A} = n, \operatorname{col}\mathbf{A} = \mathbb{R}^n and \ker\mathbf{A} = \{\mathbf{0}\}, so \mathbf{A}\mathbf{x} = \mathbf{e}_j has a unique solution \mathbf{x}_j for each axis; assembling \mathbf{X} = [\mathbf{x}_1 \cdots \mathbf{x}_n] gives \mathbf{A}\mathbf{X} = \mathbf{I} and \mathbf{X}\mathbf{A} = \mathbf{I}.
  • Why Rectangular Matrices Have No Two-Sided Inverse: If m > n (tall), \operatorname{rank}\mathbf{A} \le n < m so the map is never onto; if n > m (wide), \dim\ker\mathbf{A} \ge n - m > 0 so distinct inputs always collide.

Numerical Rule: Solve Linear Systems, Do Not Invert

Numerical Linear Algebra

  • Speed & Backward Stability: np.linalg.solve(A, b) factors \mathbf{A} via LU in \sim n^3/3 operations and guarantees a machine-precision residual \|\mathbf{A}\hat{\mathbf{x}} - \mathbf{b}\|, whereas np.linalg.inv(A) @ b costs \sim n^3 operations and inflates the residual by up to \kappa(\mathbf{A}):
H = 1 / (np.arange(10)[:, None] + np.arange(10) + 1)   # Hilbert matrix
x_true = np.ones(10)
b = H @ x_true
for x in (np.linalg.solve(H, b), np.linalg.inv(H) @ b):
    print(f'residual {np.linalg.norm(H @ x - b):.1e}, '
          f'error {np.linalg.norm(x - x_true):.1e}')
np.linalg.cond(H)
residual 5.7e-16, error 2.7e-04
residual 4.8e-05, error 9.0e-03
np.float64(16024416987428.36)

Conditioning vs. Stability: On the ill-conditioned 10 \times 10 Hilbert matrix (\kappa \approx 1.6 \times 10^{13}), solve achieves a 10^{-16} residual while inv leaves a 10^{-5} residual—and for sparse matrices, inv destroys sparsity by filling memory with dense entries.

The 2×2 Determinant as Signed Parallelogram Area

The Determinant

  • Base Times Signed Height: For columns \mathbf{u} = (p, r) and \mathbf{w} = (q, s), rotating \mathbf{u} by +90^\circ gives unit normal \mathbf{n} = (-r, p)/\|\mathbf{u}\|.
  • Lengths Cancel Cleanly: Projecting \mathbf{w} onto \mathbf{n} gives the signed height, so area is: \det\begin{bmatrix}p & q \\ r & s\end{bmatrix} = \|\mathbf{u}\|(\mathbf{w}\cdot\mathbf{n}) = ps - qr
  • Running Matrix (\det\mathbf{A} = 5): Bounding box 12 minus outer right triangles 7 equals 5, matching 1(3) - 2(-1) = 5.

Orientation Sign and Volume Collapse

Geometric Regimes

  • Three Geometric Regimes: |\det\mathbf{A}| is the area scaling factor: \det > 0 preserves counter-clockwise orientation (a), \det < 0 reverses orientation when columns swap (b), and \det = 0 collapses the square onto a line segment of zero area (c).

Three Axioms Define the n-Dimensional Determinant

General Determinant

  • 1. Multilinear in Each Column: Scaling or adding in column j scales or adds signed volume.
  • 2. Alternating (\det = 0 on Equal Columns): Coinciding columns flatten the box; swapping any two columns flips the sign.
  • 3. Normalized (\det\mathbf{I} = 1): Uniquely forces the n! permutation sum \det\mathbf{A} = \sum_\sigma \operatorname{sgn}(\sigma)\prod_j a_{\sigma(j)j}.

Triangular Matrices, Block Rules, and Cofactors

Computing Determinants

  • Triangular Shortcut: Only \sigma(j) = j avoids zeros, so \det\mathbf{U} = \prod_i u_{ii} and \det\left(\begin{smallmatrix}\mathbf{D}_1 & * \\ \mathbf{0} & \mathbf{D}_2\end{smallmatrix}\right) = \det\mathbf{D}_1\det\mathbf{D}_2.
  • Transpose Symmetry: \det\mathbf{A}^\top = \det\mathbf{A}.
  • Normalizing Flows: Triangular Jacobians turn \log|\det\mathbf{J}| = \sum_i \log|J_{ii}| into an O(d) sum instead of O(d^3).

Multiplicativity: Volume Scaling Under Composition

Multiplicativity

  • Multiplicativity (\det(\mathbf{A}\mathbf{B}) = \det\mathbf{A}\det\mathbf{B}): D(\mathbf{B}) = \det(\mathbf{A}\mathbf{B}) is multilinear and alternating in columns of \mathbf{B}, so D(\mathbf{B}) = D(\mathbf{I})\det\mathbf{B}.
  • Key Corollaries: Scalar commutativity \det(\mathbf{A}\mathbf{B}) = \det(\mathbf{B}\mathbf{A}), similarity invariance \det(\mathbf{V}\mathbf{A}\mathbf{V}^{-1}) = \det\mathbf{A}, \det(\mathbf{A}^{-1}) = 1/\det\mathbf{A}, and \det\mathbf{Q} = \pm 1.

Invertibility Criterion: det A ≠ 0

Invertibility & Volume

Proposition (Invertibility via Determinant). An n \times n matrix \mathbf{A} is invertible if and only if \det\mathbf{A} \neq 0. Equivalently, \det\mathbf{A} = 0 if and only if the columns of \mathbf{A} are linearly dependent.

  • Proof (Both Directions):
    • If \mathbf{A} is invertible, \det(\mathbf{A})\det(\mathbf{A}^{-1}) = \det\mathbf{I} = 1, which makes \det\mathbf{A} = 0 impossible.
    • If \mathbf{A} is not invertible, one column is a linear combination of the others, \mathbf{a}_j = \sum_{i \neq j} c_i \mathbf{a}_i; expanding column j by multilinearity produces a sum of determinants that each have two identical columns \mathbf{a}_i and therefore vanish.
  • Five Unified Equivalences for n \times n Matrices: Invertible \iff independent columns \iff \ker\mathbf{A} = \{\mathbf{0}\} \iff \operatorname{rank}\mathbf{A} = n \iff \det\mathbf{A} \neq 0.

Why Determinant Size Does Not Measure Conditioning

Numerical Pitfalls

  • Two Opposite Failure Modes: A tiny determinant need not mean a nearly singular matrix, and \det = 1 need not mean a well-conditioned matrix:
sign, logdet = np.linalg.slogdet(0.1 * np.eye(400))
print(np.linalg.det(0.1 * np.eye(400)), sign, logdet)
shear = np.array([[1.0, 1e8], [0.0, 1.0]])
print(np.linalg.det(shear), np.linalg.matrix_rank(shear),
      np.linalg.svd(shear, compute_uv=False))
shear[1, 0] = 1e-8
print(np.linalg.det(shear), np.linalg.matrix_rank(shear))
0.0 1.0 -921.0340371976151
1.0 1 [1.e+08 1.e-08]
0.0 1
  • Underflow vs. Ill-Conditioning: 0.1\,\mathbf{I}_{400} is perfectly conditioned (\kappa = 1, inverse 10\,\mathbf{I}_{400}) yet det underflows to 0.0 (10^{-400}, requiring slogdet), while the extreme shear \left(\begin{smallmatrix}1&10^8\\0&1\end{smallmatrix}\right) has \det = 1 yet singular values 10^8 and 10^{-8}, just 10^{-8} away from singularity.

Preview: Eigenvalues vs. Singular Values

Looking Ahead

  • Why One Scalar Is Not Enough: The determinant multiplies the directional stretches across all n dimensions into a single product, hiding whether a matrix stretches every axis evenly or crushes one axis while blowing up another.
  • Running Matrix \mathbf{A} = \left(\begin{smallmatrix}1&2\\-1&3\end{smallmatrix}\right):
    • Its eigenvalues are \lambda_{1,2} = 2 \pm i, whose product is (2+i)(2-i) = 5 = \det\mathbf{A} (§33.3).
    • Its singular values are \sigma_1 \approx 3.618 and \sigma_2 \approx 1.382, whose product is 3.618 \times 1.382 = 5 = |\det\mathbf{A}| (§33.5).
  • True Proximity to Singularity: The ratio \kappa(\mathbf{A}) = \sigma_1/\sigma_n, not \det\mathbf{A}, measures how close a matrix is to collapsing space.

Concept Check: Linear Maps, Rank & Determinants

Concept Check

  1. Commutativity Check: Do \mathbf{D} = \operatorname{diag}(2, 1) and the 90^\circ rotation \mathbf{R}_{90} = \left(\begin{smallmatrix}0&-1\\1&0\end{smallmatrix}\right) commute? Test both products on \mathbf{e}_1 = (1, 0).
  2. Rank–Nullity in Action: For \mathbf{M} = \left(\begin{smallmatrix}1&1\\2&2\end{smallmatrix}\right), what are its column space, a basis vector for its null space, its rank, and its determinant?
  3. Autoencoder Bottleneck: A linear autoencoder \mathbf{W}_2\mathbf{W}_1 maps \mathbb{R}^{100} \to \mathbb{R}^{16} \to \mathbb{R}^{100}. What is the minimum possible dimension of \ker(\mathbf{W}_2\mathbf{W}_1)?

Answers: 1. No: \mathbf{R}_{90}\mathbf{D}\mathbf{e}_1 = \mathbf{R}_{90}(2, 0) = (0, 2), whereas \mathbf{D}\mathbf{R}_{90}\mathbf{e}_1 = \mathbf{D}(0, 1) = (0, 1). 2. Both columns are (1, 2), so \operatorname{col}\mathbf{M} is the line y = 2x, \ker\mathbf{M} = \operatorname{span}\{(1, -1)\}, \operatorname{rank}\mathbf{M} = 1, and \det\mathbf{M} = 2 - 2 = 0. 3. The intermediate space has dimension 16, so \operatorname{rank}(\mathbf{W}_2\mathbf{W}_1) \le 16 and \dim\ker(\mathbf{W}_2\mathbf{W}_1) \ge 100 - 16 = 84.

Summary: Matrices as Linear Maps

Key Takeaways

Concept Mathematical Rule Geometric Meaning & Deep Learning Role
Column View \mathbf{A}\mathbf{x} = \sum_{j=1}^n x_j \mathbf{a}_j, \mathbf{a}_j = \mathbf{A}\mathbf{e}_j Columns are images of coordinate axes; fixes action on the entire input grid
Composition & einsum (\mathbf{A}\mathbf{B})_{ik} = \sum_j a_{ij}b_{jk} Applies \mathbf{B} then \mathbf{A}; einsum generalizes contractions to 4D attention tensors
Orthogonal Matrix \mathbf{Q}^\top\mathbf{Q} = \mathbf{I} \iff \mathbf{Q}^{-1} = \mathbf{Q}^\top Rigid rotation/reflection preserving dot products, Euclidean norms, and angles
Rank–Nullity Theorem \operatorname{rank}\mathbf{A} + \dim\ker\mathbf{A} = n Surviving dimensions (\operatorname{col}\mathbf{A}) plus erased dimensions (\ker\mathbf{A}) equal input width n
Invertibility & solve \ker\mathbf{A} = \{\mathbf{0}\} \iff \operatorname{rank}\mathbf{A} = n \iff \det\mathbf{A} \neq 0 Square map is one-to-one and onto; always use solve(A, b) (n^3/3), never inv(A)
Determinant Volume \det(\mathbf{A}\mathbf{B}) = \det\mathbf{A}\det\mathbf{B}, \det\mathbf{U} = \prod_i u_{ii} Signed volume scaling factor; triangular Jacobians give O(n) slogdet in flows