Linear Algebra, Vector Spaces & Matrix Calculus
Vector norms, geometric projections, trace derivative identities, and multivariate matrix calculus.
Reference notes. Condensed summaries of each topic, not step-by-step lessons. The Core Course is the one to work through.
Inspect Architecture: Linear regression1. The idea
Every machine learning dataset lives inside a vector space R^D, and every neural network layer applies a parameterized affine transformation W x + b followed by coordinate-wise non-linear curvature. Matrix calculus provides the exact formal mechanics for computing how scalar loss functions change with respect to multidimensional weight matrices.
2. The math
• Let the residual error matrix be E = XW - Y in R^(N x K).
• Express the Frobenius norm using the trace operator: ||E||_F^2 = Tr(E^T E) = Tr((XW - Y)^T (XW - Y)).
• Expand the terms inside the trace: Tr(W^T X^T X W - W^T X^T Y - Y^T X W + Y^T Y).
• Apply the trace derivative identity ∇_W Tr(W^T A W) = (A + A^T) W = 2 A W (since A = X^T X is symmetric), and ∇_W Tr(A W) = A^T:
• ∇_W ||XW - Y||_F^2 = 2 X^T X W - 2 X^T Y = 2 X^T (X W - Y). Q.E.D.
3. How it works
4. The code (python)
import numpy as np
# Numerical vs Analytical Matrix Gradient Verification
def check_matrix_gradient(N=50, D=5, K=2, eps=1e-5):
np.random.seed(42)
X = np.random.randn(N, D)
W = np.random.randn(D, K)
Y = np.random.randn(N, K)
# Analytical gradient: (2/N) * X^T (X W - Y)
grad_analytical = (2.0 / N) * np.dot(X.T, (np.dot(X, W) - Y))
# Numerical gradient via central finite difference
grad_numerical = np.zeros_like(W)
for i in range(D):
for j in range(K):
W_pos = W.copy(); W_pos[i, j] += eps
W_neg = W.copy(); W_neg[i, j] -= eps
loss_pos = np.mean((np.dot(X, W_pos) - Y)**2)
loss_neg = np.mean((np.dot(X, W_neg) - Y)**2)
grad_numerical[i, j] = (loss_pos - loss_neg) / (2.0 * eps)
max_diff = np.max(np.abs(grad_analytical - grad_numerical))
print(f"Analytical vs Numerical Gradient Max Difference: {max_diff:.2e}")
assert max_diff < 1e-6, "Gradient check failed!"
print("✓ Matrix Calculus Gradient Identity Verified Successfully.")
if __name__ == "__main__":
check_matrix_gradient()5. Check yourself
In the catalog
Finished this chapter?
The Epoch Zero newsletter
What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.