Chapter 4 of 10 · ~22 min read & lab+55 XP
Chapter 4 · Linear Algebra

Solving Linear Systems (Ax = b), Gaussian Elimination & Inverses

Row vs. Column geometry, the 3 outcomes of Ax = b, step-by-step Gaussian elimination, matrix inverses, and LU/Cholesky solvers

Why ML Engineers & Data Scientists Actually Need This

Solving Ax = b is how Linear Regression, Ridge, Kalman Filters, and Newton's Method find exact optimal parameters!

ML / AI Engineer

Never write `np.linalg.inv(A) @ b` in production! Understanding LU/Cholesky elimination explains why `np.linalg.solve(A, b)` is 3× faster and vastly more numerically accurate.

Data Scientist

Knowing when Ax = b has 0, 1, or ∞ solutions immediately diagnoses why your regression model threw `LinAlgError: Singular matrix` on real tabular data.

Interview & Debug Edge

A top ML systems question: 'Why shouldn't you explicitly invert (XᵀX) to solve OLS regression, and what should you use instead?' (Answer: `np.linalg.solve` / QR / SVD!).

Step 0 · Test Your Gut Before Any Math!

You need to solve Ax = b in Python/NumPy for a 2,000 × 2,000 matrix A. Which line of code is BOTH faster AND more numerically accurate?

What You Will Master in This Chapter
  • Translate any system of linear equations into matrix form Ax = b and visualize both the Row Picture and Column Picture.
  • Classify any system immediately into its 3 possible outcomes: Unique solution, No solution (inconsistent), or Infinitely many solutions.
  • Solve linear systems by hand using Augmented Matrices [A | b], Elementary Row Operations, Gaussian Elimination, and Back-Substitution.
  • Compute 2×2 matrix inverses by hand and understand why production ML uses LU/Cholesky `np.linalg.solve` instead of explicit `np.linalg.inv`.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“A times x equals b”
Plain-English Meaning
A compact way to write 100 simultaneous linear equations at once — find the hidden recipe x that produces target b!
Everyday Example
Finding weights w in Ridge Regression: (XᵀX + λI) w = Xᵀy.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Solving Ax=bA\mathbf{x} = \mathbf{b} is the central computational problem of Linear Algebra. Whether you are finding the exact intersection of two lines in high school algebra or solving a 10,000-variable Ridge regression system in production, the exact same geometry and elimination mechanics apply!

1. Two Geometric Pictures of Ax = b & Its 3 Possible Outcomes

Everyday Story First (Zero Math Yet!)

Suppose you buy 1 coffee + 1 muffin for $4 (x + y = 4), and your friend tells you coffee costs the same as a muffin (x − y = 0). Instantly you know both cost $2! Each equation is a straight line, and solving Ax = b is literally asking: where do the lines cross?

Switch between the 3 fates of ANY linear system below!

1. Unique Solutiondet(A) ≠ 0 · Lines cross once2. No Solution (Inconsistent)det(A) = 0 · Parallel lines3. Infinitely Many Solutionsdet(A) = 0 · Same line twice
Figure 4.1 — The 3 Possible Outcomes of a Linear System Ax = b: Unique intersection, Parallel lines (no solution), or Coincident lines (infinitely many).

Consider the tiny 2-equation system: {2x+y=54x+5y=13⟺[2145]⏟A[xy]⏟x=[513]⏟b\begin{cases} 2x + y = 5 \\ 4x + 5y = 13 \end{cases} \quad \Longleftrightarrow \quad \underbrace{\begin{bmatrix} 2 & 1 \\ 4 & 5 \end{bmatrix}}_{A} \underbrace{\begin{bmatrix} x \\ y \end{bmatrix}}_{\mathbf{x}} = \underbrace{\begin{bmatrix} 5 \\ 13 \end{bmatrix}}_{\mathbf{b}}

There are two powerful ways to picture Ax=bA\mathbf{x} = \mathbf{b}:

  1. The Row Picture (Intersecting Lines/Planes): Each row is one linear equation — a line in 2D (or a plane in 3D). The solution (x,y)(x, y) is the point where all lines intersect!
  2. The Column Picture (Linear Combination): Rewrite Ax=bA\mathbf{x} = \mathbf{b} as: x[24]+y[15]=[513]x\begin{bmatrix}2\\4\end{bmatrix} + y\begin{bmatrix}1\\5\end{bmatrix} = \begin{bmatrix}5\\13\end{bmatrix} We are asking: "Which weights x,yx, y combine the columns of AA to hit target b\mathbf{b}?"

Every Linear System Has Exactly ONE of 3 Outcomes

No matter if you have 2 variables or 2 million variables, Ax=bA\mathbf{x} = \mathbf{b} can NEVER have 2 or 3 distinct solutions — only:

  1. Exactly 1 Unique Solution: Lines cross at a single point (det⁡(A)≠0\det(A) \ne 0, full rank).
  2. Zero Solutions (Inconsistent): Parallel lines that never touch (e.g., x+y=2x + y = 2 and x+y=5x + y = 5).
  3. Infinitely Many Solutions: Redundant equations describing the same line/plane (at least one free variable).
Hands-On Mini-Lab · Every Linear System Ax = b Has Only 3 Possible Fates!
Case 1: 1 Unique Solution (Lines Cross Once!)
Eq 1: x + y = 4
Eq 2: x − y = 0
det(A) = −2 ≠ 0 (Invertible!)

Each equation gives genuinely NEW information — they meet cleanly at (x=2, y=2)!

Try It Yourself

Without solving completely, classify the system: (1) x + 2y = 4 and (2) 2x + 4y = 10. Does it have 1, 0, or infinitely many solutions?

2. Gaussian Elimination & Row Echelon Form (Step-by-Step)

Everyday Story First (Zero Math Yet!)

How does a computer solve 1,000 equations with 1,000 unknowns without guessing? Gaussian Elimination — the exact high-school trick of subtracting multiples of Equation 1 from Equation 2 to knock out variables one by one until the system looks like a neat staircase (upper triangular) that unravels from the bottom up!

1. Augmented [A | b][ 2 1 | 5 ][ 4 5 | 13 ]R₂ ← R₂ − 2R₁→2. Row Echelon (Upper Δ)[ 2 1 | 5 ][ 0 3 | 3 ]Back-Sub→3. Exact Solution3y = 3 ⇒ y = 12x + 1 = 5 ⇒ x = 2
Figure 4.2 — Gaussian Elimination Staircase: use row operations to create zeros below each pivot, then back-substitute from the bottom row up.

To solve Ax=bA\mathbf{x} = \mathbf{b} systematically for any size nn, pack AA and b\mathbf{b} into an Augmented Matrix [A∣b][A \mid \mathbf{b}] and apply the 3 Legal Elementary Row Operations (which never change the solution!):

  1. Swap two rows (Ri↔RjR_i \leftrightarrow R_j).
  2. Scale a row by any non-zero constant (Ri←cRiR_i \leftarrow c R_i).
  3. Add a multiple of one row to another (Ri←Ri+cRjR_i \leftarrow R_i + c R_j).

Worked Example 1 — Solving a 3×3 System by Hand

Solve: {x+y+z=62x+3y+z=11x−y+2z=5⟹[1116231111−125]\begin{cases} x + y + z = 6 \\ 2x + 3y + z = 11 \\ x - y + 2z = 5 \end{cases} \quad \Longrightarrow \quad \left[\begin{array}{ccc|c} 1 & 1 & 1 & 6 \\ 2 & 3 & 1 & 11 \\ 1 & -1 & 2 & 5 \end{array}\right]

  • Step 1 (Eliminate Column 1 below pivot 11):
    • R2←R2−2R1R_2 \leftarrow R_2 - 2R_1: [0,1,−1∣−1][0, 1, -1 \mid -1]
    • R3←R3−R1R_3 \leftarrow R_3 - R_1: [0,−2,1∣−1][0, -2, 1 \mid -1]
  • Step 2 (Eliminate Column 2 below pivot 11):
    • R3←R3+2R2R_3 \leftarrow R_3 + 2R_2: [0,0,−1∣−3][0, 0, -1 \mid -3] [111601−1−100−1−3](Upper Triangular / Row Echelon Form!)\left[\begin{array}{ccc|c} \mathbf{1} & 1 & 1 & 6 \\ 0 & \mathbf{1} & -1 & -1 \\ 0 & 0 & \mathbf{-1} & -3 \end{array}\right] \quad \text{(Upper Triangular / Row Echelon Form!)}
  • Step 3 (Back-Substitution from bottom row up):
    1. Row 3: −z=−3  ⟹  z=3-z = -3 \implies \mathbf{z = 3}
    2. Row 2: y−3=−1  ⟹  y=2y - 3 = -1 \implies \mathbf{y = 2}
    3. Row 1: x+2+3=6  ⟹  x=1x + 2 + 3 = 6 \implies \mathbf{x = 1}
  • Check: 1+2+3=61+2+3=6, 2(1)+3(2)+3=112(1)+3(2)+3=11, 1−2+2(3)=51-2+2(3)=5. Exact!

(In computer science, recording the elimination multipliers produces LU Factorization A=LUA = LU, costing O(23n3)O(\frac{2}{3}n^3) once — and only O(n2)O(n^2) for every new right-hand side b\mathbf{b}!)

Walk Through With Me · Interactive Worked Example

Solving a 2×2 System by Hand via Elimination (3 Easy Steps)

Solve: (1) 2x + y = 5, and (2) 4x + 3y = 11.

1Eliminate x from Equation (2)Step 1 / 3

Subtract 2×Eq (1)2 \times \text{Eq (1)} from Eq (2) so the 4x4x cancels cleanly: (4x+3y)−2(2x+y)=11−2(5)  ⟹  y=1(4x + 3y) - 2(2x + y) = 11 - 2(5) \implies \mathbf{y = 1}

Teacher's Note: Knocking out the bottom-left entry turns the matrix into a clean upper triangle!
Try It Yourself

Use Gaussian elimination to solve: 2x + y = 5 and 4x + 5y = 13.

3. Matrix Inverses (A⁻¹) & Why Production Code Uses Solve Instead

Everyday Story First (Zero Math Yet!)

Think of a matrix inverse A⁻¹ as Ctrl+Z (Undo)! If A rotates an image 30° clockwise, A⁻¹ rotates it 30° counter-clockwise. If A multiplies a price by 2, A⁻¹ divides by 2. When does Ctrl+Z FAIL? When A destroys information (like multiplying by 0 or squashing a 3D photo flat into 2D — you can't un-squash a pancake!).

xMultiply by Ab = AxUndo with A⁻¹ (only if det(A) ≠ 0)2×2 Inverse FormulaA⁻¹ = 1/(ad−bc) · [[d, -b], [-c, a]]Swap diagonal, negate off-diagonal, divide by det!
Figure 4.3 — Matrix Inverse as an Undo Machine: A⁻¹ reverses A exactly when det(A) ≠ 0; if space collapses onto a line, no undo exists.

For a square matrix A∈Rn×nA \in \mathbb{R}^{n \times n}, its inverse A−1A^{-1} is the unique matrix that completely undoes AA:

A−1A=AA−1=InA^{-1} A = A A^{-1} = I_n

When A−1A^{-1} exists (called invertible or non-singular, which happens if and only if det⁡(A)≠0\det(A) \ne 0), multiplying both sides of Ax=bA\mathbf{x} = \mathbf{b} on the left by A−1A^{-1} gives x=A−1b\mathbf{x} = A^{-1}\mathbf{b}.

The 2×2 Inverse Shortcut (Memorize This!)

A=[abcd]  ⟹  A−1=1ad−bc[d−b−ca]A = \begin{bmatrix} a & b \\ c & d \end{bmatrix} \implies A^{-1} = \frac{1}{ad - bc} \begin{bmatrix} d & -b \\ -c & a \end{bmatrix} (Swap the main diagonal a↔da \leftrightarrow d, flip the signs of off-diagonals −b,−c-b, -c, and divide by det⁡(A)=ad−bc\det(A) = ad - bc!)

Worked Example 2 — Computing a 2×2 Inverse & Checking A−1A=IA^{-1}A = I

Let A=[4726]A = \begin{bmatrix} 4 & 7 \\ 2 & 6 \end{bmatrix}:

  1. Determinant: det⁡(A)=(4)(6)−(7)(2)=24−14=10≠0\det(A) = (4)(6) - (7)(2) = 24 - 14 = \mathbf{10} \ne 0 (invertible!).
  2. Swap & negate: A−1=110[6−7−24]=[0.6−0.7−0.20.4]A^{-1} = \frac{1}{10}\begin{bmatrix} 6 & -7 \\ -2 & 4 \end{bmatrix} = \begin{bmatrix} 0.6 & -0.7 \\ -0.2 & 0.4 \end{bmatrix}.
  3. Verify: AA−1=110[24−14−28+2812−12−14+24]=[1001]=I2A A^{-1} = \frac{1}{10}\begin{bmatrix} 24-14 & -28+28 \\ 12-12 & -14+24 \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} = I_2!

Inverse Product Rule

Just like transpose, taking the inverse of a product reverses order: (AB)−1=B−1A−1(AB)^{-1} = B^{-1} A^{-1}.

Formula Anatomy · Click Any Colored Piece to Decode It
2×2 Inverse Trick: A⁻¹ = (1 / (ad − bc)) · [[d, −b], [−c, a]]

Swap the main diagonal, flip signs on the off-diagonal, and divide by det(A) = ad − bc!

Divide by Determinant (Danger Check!)

If ad − bc = 0, you'd be dividing by ZERO — proving A is Singular and has NO inverse!

In our example: For [[2, 1], [4, 3]]: ad − bc = 6 − 4 = 2 ≠ 0 ✓
Put it together with real numbers: Check: [[2,1],[4,3]] @ (0.5·[[3,−1],[−4,2]]) = [[1,0],[0,1]] = I! Exact undo!
Pause & Check · Quick Intuition Pulse

Pause & Check: Why can a linear system Ax = b NEVER have 'exactly 2 solutions'?

Try It Yourself

Find the inverse of A = [[3, 1], [5, 2]] by hand, and use it to solve Ax = [4, 7]ᵀ.

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

YES — what an awesome catch!! Real ML tables are tall and skinny (100,000 × 10), so no straight line passes through all 100,000 noisy data points exactly (0 solutions). That's why in Chapter 7 (Least Squares) we project y onto the closest reachable point by solving the square 10×10 Normal Equations (XᵀX)w = Xᵀy!

Interactive Visual Lab
Lab Challenge: Adjust slopes m₁ and m₂ (or click 'Parallel (No Sol)') to make the two lines parallel (det(A) = 0, inconsistent system)!
(2.0, 3.0)
Eq 1: -1.0x + 1.0y = 1.0
Eq 2: 0.5x + 1.0y = 4.0
Slope m₁1.0
Intercept c₁1.0
Slope m₂-0.5
Intercept c₂4.0
det(A) = m₂ − m₁-1.50
Unique Solution: x = 2.00, y = 3.00
Geometric Takeaway: Every linear system Ax = b has 1 unique, 0, or ∞ solutions. Gaussian elimination (LU/Cholesky) solves Ax = b stably in O(n³) without ever explicitly forming A⁻¹.
Where This Powers Real ML, Deep Learning & GenAI

Ridge Regression & Kernel Ridge Solvers

Solving (XᵀX + λI)w = Xᵀy uses Cholesky decomposition (A = LLᵀ, 2× faster than LU) because XᵀX + λI is symmetric positive definite!

Gaussian Processes (Cholesky Solve)

GP posterior inference computes (K + σ²I)⁻¹y via Cholesky triangular solves instead of ever inverting the N×N covariance kernel matrix K.

Newton's Method & Second-Order Optimizers (L-BFGS)

Each Newton optimization step solves the linear system H Δθ = −∇L for the update direction Δθ using Hessian curvature H.

Overdetermined Systems (N ≫ D) → Least Squares

Real ML datasets have far more rows (equations) than features (unknowns), so Ax = b has no exact solution — transitioning directly into Least Squares projection!

Production NumPy & PyTorch Code Patterns
import numpy as np

A = np.array([[2.0, 1.0],
              [4.0, 5.0]])
b = np.array([5.0, 13.0])

# ✓ BEST PRACTICE: Direct LU solver — faster & far more accurate than inv(A) @ b
x = np.linalg.solve(A, b)              # array([2., 1.])

# ✓ For Symmetric Positive Definite matrices (e.g. Ridge XᵀX + λI):
# Cholesky factorization A = L @ L.T is 2× faster than general LU!
M = A.T @ A + 0.1 * np.eye(2)
L = np.linalg.cholesky(M)              # lower-triangular factor
y = np.linalg.solve(L, A.T @ b)        # forward substitution
w = np.linalg.solve(L.T, y)            # back substitution

# ✓ Overdetermined / singular systems (never crashes with LinAlgError):
x_ls, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Writing `np.linalg.inv(A) @ b` instead of `np.linalg.solve(A, b)`
Best Practice: Computing the explicit inverse takes ~2–3× more FLOPs AND suffers significantly larger floating-point rounding error. Always use `np.linalg.solve` (or `scipy.linalg.cho_solve` for SPD matrices).
Trap #2: Calling `np.linalg.solve` on a non-square or singular matrix
Best Practice: `np.linalg.solve` requires a square invertible matrix and raises `LinAlgError` on singular inputs. Use `np.linalg.lstsq` for rectangular or rank-deficient ML problems.
Trap #3: Thinking `(A + B)⁻¹ = A⁻¹ + B⁻¹`
Best Practice: Inverses do NOT distribute over addition! Only products invert cleanly via `(AB)⁻¹ = B⁻¹A⁻¹`.
Chapter Mastery Check (+55 XP)
Score: 0 / 5
1Which of the following is IMPOSSIBLE as the number of solutions to a linear system Ax = b?
2What is the inverse of A = [[2, 1], [5, 3]]?
3After Gaussian elimination on [A | b], the bottom row reads [0, 0, 0 | 7]. What does this mean?
4Why should you prefer `np.linalg.solve(A, b)` over `np.linalg.inv(A) @ b` in ML code?
5If A and B are both invertible n×n matrices, what equals (AB)⁻¹?

Apply What You Learned — Solve Matching Coding Problems