Matrix Transformations: Visualizing Linear Algebra for Machine Learning
Stop viewing matrices as data containers. Learn how neural networks use linear algebra as an active engine to geometrically fold, shear, and crush high-dimensional space.
Thereβs a particular wall that people hit when studying deep learning β somewhere around the point where the tutorials run out and the papers begin. The PyTorch calls still work, the loss still goes down, but nothing quite makes sense anymore. Gradients vanish. Models donβt converge. Architectures that βshouldβ work donβt.
Nine times out of ten, the root cause is that matrices were never understood as anything other than data containers β glorified spreadsheets. That framing is useful for storage, but it actively obscures what a neural network is doing to your data.
In linear algebra, a matrix is an active transformation of space. When a feed-forward layer processes an input, it isnβt querying a table. Itβs warping the geometric coordinate system the data lives in β rotating it, scaling it, shearing it β until the structure of the data becomes legible. Everything else in deep learning is built on top of that operation.
The Coordinate System Is Not Fixed
Before we can talk about transforming space, we need to be precise about what defines it.
Any point in a 2D plane is specified by two numbers: how far it travels horizontally and how far it travels vertically. But that description depends on what βhorizontalβ and βverticalβ mean β and those directions are defined by two foundational vectors we call basis vectors:
- : one unit to the right,
- : one unit upward,
Every vector in 2D space is a linear combination of these two. When you write , youβre saying: take , scale it by 3, take , scale it by 2, add them:
The key shift: the grid itself is downstream of and . Move the basis vectors, and every point in the space moves with them β because every point was defined in terms of those vectors. A matrix is precisely a description of where the basis vectors land after a transformation.
Matrices as Spatial Instructions
A matrix encodes exactly two pieces of information: the new position of (first column) and the new position of (second column):
The first column is where lands. The second column is where lands. Matrix-vector multiplication then follows from that definition directly: to find where input ends up, scale the new by and the new by , then add:
The Shear Transformation
A shear transformation pushes one axis while leaving the other fixed. To shear horizontally β sliding the top of the space right while keeping the bottom anchored β we leave in place and push one unit to the right:
Apply this to an arbitrary point:
A square input becomes a parallelogram. This is, geometrically, what happens to your data in the first dense layer of a network.
Determinant: How Much Does Space Scale?
The determinant of a matrix measures how much the transformation scales area. If the original input occupies a region of area 1, after applying , that region has area :
For above: . Area is preserved β the parallelogram has the same area as the original square.
A negative determinant means the transformation flips orientation (a reflection is involved). And a determinant of exactly zero means the transformation is singular: the entire 2D plane collapses into a line (or a point).
Dimensional Collapse
This is the degenerate case worth understanding carefully. Consider:
The new is and the new is . Notice that β theyβre collinear. When the two basis vectors land on the same line, the entire 2D plane gets crushed onto that line. Every point that was anywhere in the plane is mapped to some point on that one diagonal.
Verify: . Zero determinant, collapsed space.
This is irreversible. Once youβve crushed a 2D plane to a 1D line, you canβt reconstruct where any particular point came from β infinitely many input points map to the same output. Thereβs no inverse matrix because information has been permanently destroyed.
In ML, this collapse is used intentionally. Embedding layers and autoencoders use non-square weight matrices to project high-dimensional data into lower-dimensional spaces, discarding redundant dimensions and keeping the principal structure. The non-invertibility isnβt a bug; itβs the compression step.
Linear Layers in Neural Networks
A dense (fully connected) layer implements:
Each term has a geometric role:
applies the transformation β rotating, scaling, shearing the space. This part is a linear map: lines stay lines, the origin stays fixed.
is a translation, shifting the entire transformed space by a constant offset. This breaks the origin-fixed constraint of pure linear maps and produces an affine transformation (linear transformation + translation). Without the bias, a neuron with zero input would always output zero regardless of weights, which severely limits representational capacity.
The goal during training is to find a and that reshapes the input space so that whatever youβre trying to predict β spam vs. not spam, cat vs. dog β becomes geometrically separable. Backpropagation is the algorithm that calculates how to adjust the entries of to move the loss in the right direction.
Why Depth Alone Doesnβt Help: The Linearity Collapse Problem
Hereβs the architectural trap. Suppose we stack three dense layers with no activation functions between them:
The final expression has the form , where both and are just constants. Three layers of linear transformations collapse into one single affine map. A network with 1,000 such layers is mathematically equivalent to one with exactly one.
The consequence: a purely linear network can only learn linear decision boundaries. No matter how many layers you add, it can only draw hyperplanes through the data. Spirals, concentric rings, XOR β none of these are linearly separable, and a linear model cannot learn them at any depth.
Nonlinearity: Breaking the Collapse
The solution is to introduce a nonlinear function between layers β an activation function β that breaks the composability of linear maps.
The most common choice is ReLU (Rectified Linear Unit):
ReLU sets all negative values to zero and leaves positives unchanged. Applied element-wise after each linear layer, it folds the transformed space: any coordinates pushed into negative territory get snapped to the axis. This folding is genuinely nonlinear β it cannot be represented by any matrix β so the composability argument no longer applies. Three ReLU layers are not equivalent to one.
Why ReLU specifically, rather than Sigmoid or tanh? The short answer is that Sigmoid and tanh both saturate: for large inputs (positive or negative), their gradients approach zero. During backpropagation through deep networks, this causes gradients to vanish β updates to early layers become negligible, and the network stops learning. ReLU doesnβt saturate on the positive side, so gradients flow through cleanly. The cost is βdead neuronsβ (units stuck outputting zero when their input is persistently negative), which is why variants like Leaky ReLU or GELU are used in practice, but the core motivation is gradient preservation.
Implementation: Tracing a Vector Through a Layer
The following demonstrates a single dense layer with ReLU, tracking what happens to a specific input vector at each step. One thing to notice: no explicit loops over data points. The @ operator performs matrix multiplication on the entire batch simultaneously, which on modern hardware maps directly to SIMD vector instructions.
import numpy as np
def relu(x: np.ndarray) -> np.ndarray: return np.maximum(0, x)
# Weight matrix and bias for a single dense layerW = np.array([ [ 1.5, -0.5], [ 0.8, 2.0]])
b = np.array([[-1.0], [-0.5]])
# A single input vector in the bottom-right quadrantx = np.array([[1.0], [-1.0]])
print("Input vector:")print(x)
linear_out = (W @ x) + bprint("\nAfter linear transform (W @ x + b):")print(linear_out)
final_out = relu(linear_out)print("\nAfter ReLU:")print(final_out)Input vector:[[ 1.] [-1.]]
After linear transform (W @ x + b):[[ 1. ] [-1.7]]
After ReLU:[[1.] [0.]]The input started at . The weight matrix and bias moved it to . ReLU then clamped the negative -component to zero, landing it at on the horizontal axis.
That sequence β linear map, then nonlinear clamp β is the atomic operation that every layer in a feed-forward network repeats. Stack enough of them, and the network can carve out arbitrarily complex decision regions in the input space. The training process (gradient descent + backpropagation) is entirely about finding the and values that make those regions align with the labels in your data.
Understanding that the weights are spatial instructions, not lookup values, is what makes the rest of the math fall into place: why initialization matters (youβre setting the initial geometry), why batch normalization helps (it reconditions the transformed space between layers), and why very deep networks without residual connections struggle (the effective transformation accumulates numerical instability across many matrix products).
Author
Varkin Academy