Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsLinear Algebra

Inverse and linear systems

P1.B945 min●●○ IntermediateReviewed Nov 30, 2026

Why this matters for machine learning

An inverse undoes a matrix, and “which input gave this output?” is the question behind every linear system Ax=b\mathbf{A}\mathbf{x}=\mathbf{b}, so knowing when the answer exists, is unique and is trustworthy decides whether your code works.

  • The best weights of linear regression solve the linear system X⊤Xw=X⊤y\mathbf{X}^\top\mathbf{X}\mathbf{w}=\mathbf{X}^\top\mathbf{y}. (P3.A2: Linear regression, coming soon)
  • Ridge regression adds λI\lambda\mathbf{I} with λ>0\lambda>0, so that this matrix is always invertible, even when two features are redundant. (P3.A6: Regularization: L1 and L2, coming soon)
  • Newton's method finds each step by solving a linear system with the Hessian matrix. (P1.F6: Second-order methods, coming soon)
  • Normalizing flows are built from maps that can be undone, so every step needs an inverse that is cheap to compute. (P8.6: Autoregressive image models and flows, coming soon)

Before this: Matrices as data and as transformations, Matrix multiplication, Span, independence, basis and rank, The determinant

After this lesson you can

  • Say what the inverse of a matrix is (the map that undoes it, AA−1=A−1A=I\mathbf{A}\mathbf{A}^{-1}=\mathbf{A}^{-1}\mathbf{A}=\mathbf{I}), compute a 2×22\times2 inverse, and decide whether an inverse exists
  • Use (AB)−1=B−1A−1(\mathbf{A}\mathbf{B})^{-1}=\mathbf{B}^{-1}\mathbf{A}^{-1} and the other inverse rules, and write down the inverse of a diagonal matrix, a rotation, a shear and a reflection
  • Read Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} as lines that meet and as a combination of the columns, decide between one, no and infinitely many solutions, and solve a system by elimination and back substitution
  • Explain why code solves instead of inverting, what a large condition number does to errors, and what np.linalg.solve and LinAlgError mean

A matrix warps the plane: in P1.B5 a square grid turned into a slanted one. This lesson asks two questions that sound different and are really one. Can the warp be run backwards? And: if you are told where a point ended up, where did it start? The first question leads to the inverse of a matrix. The second is a linear system Ax=b\mathbf{A}\mathbf{x}=\mathbf{b}, one of the most common problems in all of numerical computing. We also learn why good code almost never computes an inverse, even though the inverse is the idea that explains everything.

Undoing a transformation

Take the matrix from P1.B8, with columns (2,1)(2,1) and (−1,2)(-1,2):

A=(2−112)\mathbf{A}=\begin{pmatrix}2&-1\\1&2\end{pmatrix}

It sends the point (1,1)(1,1) to A(11)=(2−11+2)=(13)\mathbf{A}\binom11=\binom{2-1}{1+2}=\binom13. Now we ask the reverse question: is there a matrix that takes (1,3)(1,3) back to (1,1)(1,1), and in the same way every other output back to its input? There is, and it is

A−1=15(21−12)=(0.40.2−0.20.4)\mathbf{A}^{-1}=\frac15\begin{pmatrix}2&1\\-1&2\end{pmatrix}=\begin{pmatrix}0.4&0.2\\-0.2&0.4\end{pmatrix}

(the 2×22\times2 formula previewed in P1.B8; the next sections explain it). Check on our point: A−1(13)=15(2+3−1+6)=(11)\mathbf{A}^{-1}\binom13=\frac15\binom{2+3}{-1+6}=\binom11. It works.

The inverse of a square matrix A\mathbf{A} is the matrix A−1\mathbf{A}^{-1} that undoes it:

A−1A=IandAA−1=I\mathbf{A}^{-1}\mathbf{A}=\mathbf{I}\qquad\text{and}\qquad\mathbf{A}\mathbf{A}^{-1}=\mathbf{I}

Here I\mathbf{I} is the identity matrix, the map that does nothing (P1.B5): every point stays where it is. By P1.B6, A−1A\mathbf{A}^{-1}\mathbf{A} means “first A\mathbf{A}, then A−1\mathbf{A}^{-1}”, so the equation says that warping and then unwarping leaves every point where it started. The second equation says the same the other way round: unwarping and then warping.

The widget lets you watch this. Slide Step from 00 to 11 and the grid and the F are warped by A\mathbf{A}. Keep going to 22 and A−1\mathbf{A}^{-1} carries everything back.

Warp the plane with A, then undo it with A⁻¹

−3−2−1123−3−2−1123p

Original position. Slide right to apply A.

A = 2−1 12
A⁻¹ = 0.40.2 −0.20.4
det = A₁₁×A₂₂ − A₁₂×A₂₁ = 5, and A⁻¹ = (1/5) × the matrix with 2, 1 on top and −1, 2 below.
Check: A⁻¹A = (1, 0; 0, 1), the identity.
p = (1, 1) → A p = (1, 3) → A⁻¹(A p) = (1, 1)
Condition number (largest stretch ÷ smallest stretch): 1

Grey: the original grid, unit square and “F”. Blue: where the slider has moved them. The ring is where the test point p starts (drag it) and the filled dot is where it is now. When A squashes the plane, a second point q appears that lands on the same spot. Entries are shown rounded to 3 decimals.

Inverse warp. The Step slider runs from 0 (original) through 1 (after A) to 2 (after A and then its inverse). The four sliders edit A. The ring is the test point p (drag it, or use the arrow keys) and the filled dot shows where it is now. The readouts show A, its inverse (or “does not exist”), a check of A⁻¹A, the path of p, and the condition number. When A squashes the plane, a second point q appears that lands on the same spot as p, and the slider stops at 1.

Things to try:

  1. Drag Step from 00 to 22. At 22 the grid, the F and the test point are exactly where they started. The readout shows A−1=(0.40.2−0.20.4)\mathbf{A}^{-1}=\begin{pmatrix}0.4&0.2\\-0.2&0.4\end{pmatrix} and the check says A−1A\mathbf{A}^{-1}\mathbf{A} is the identity.
  2. Press Rotate 30°. The inverse is a rotation by 30∘30^\circ the other way, and its entries are the same numbers with the signs of the off-diagonal entries swapped.
  3. Press Stretch (the matrix (2000.5)\begin{pmatrix}2&0\\0&0.5\end{pmatrix}). The inverse shrinks xx by half and stretches yy by 22: it is (0.5002)\begin{pmatrix}0.5&0\\0&2\end{pmatrix}.
  4. Press Shear. The inverse is the shear the other way, (1−101)\begin{pmatrix}1&-1\\0&1\end{pmatrix}. Press Reflect: the inverse is the same matrix, because mirroring twice puts everything back.
  5. Press Squash or Projection. The Undo button is switched off and the slider stops at 11. A second point q\mathbf{q} appears, a different point from p\mathbf{p}, and both dots land in the same place. Which of the two would the inverse send it back to? It cannot be both, so there is no inverse.
  6. Press Nearly squashed (the matrix (1111.02)\begin{pmatrix}1&1\\1&1.02\end{pmatrix}). An inverse exists, but its entries are 5151 and −50-50, and the status warns about the condition number. We come back to this at the end.

Intuition

Think of rewinding a film. If the film (the warp) lost nothing, you can play it backwards and get the original frame. The inverse is that backwards film. It exists exactly when each output frame came from only one input frame.

The analogy breaks when something is thrown away. Scrambling an egg cannot be rewound: many different arrangements of the egg lead to the same scramble. A matrix that squashes the plane onto a line is like that, and it is the case in which an inverse does not exist.

Math

For a square matrix A\mathbf{A}, an inverse is a matrix A−1\mathbf{A}^{-1} with A−1A=AA−1=I\mathbf{A}^{-1}\mathbf{A}=\mathbf{A}\mathbf{A}^{-1}=\mathbf{I}. It is unique: if B\mathbf{B} and C\mathbf{C} both undo A\mathbf{A}, then

B=BI=B(AC)=(BA)C=IC=C.\begin{aligned} \mathbf{B}&=\mathbf{B}\mathbf{I}=\mathbf{B}(\mathbf{A}\mathbf{C}) \\ &=(\mathbf{B}\mathbf{A})\mathbf{C}=\mathbf{I}\mathbf{C}=\mathbf{C}. \end{aligned}

That is why we say “the” inverse. The inverse is itself a matrix, so it is a linear map too. Taking the determinant of AA−1=I\mathbf{A}\mathbf{A}^{-1}=\mathbf{I} and using det⁡(AB)=det⁡Adet⁡B\det(\mathbf{A}\mathbf{B})=\det\mathbf{A}\det\mathbf{B} from P1.B8 gives det⁡A⋅det⁡A−1=1\det\mathbf{A}\cdot\det\mathbf{A}^{-1}=1, so det⁡A−1=1/det⁡A\det\mathbf{A}^{-1}=1/\det\mathbf{A}. For our A\mathbf{A} this is 1/5=0.21/5=0.2, and indeed 0.4⋅0.4−0.2⋅(−0.2)=0.16+0.04=0.20.4\cdot0.4-0.2\cdot(-0.2)=0.16+0.04=0.2.

Code

import numpy as np

A = np.array([[2.0, -1.0], [1.0, 2.0]])
A_inv = np.linalg.inv(A)
print(A_inv)        # [[ 0.4  0.2]
                    #  [-0.2  0.4]]
print(A_inv @ A)    # the identity (up to rounding)

np.linalg.inv returns the inverse of a square array. The NumPy section below shows how to check it, and why you will rarely need it.

Where the 2×22\times2 formula comes from

How do you find A−1\mathbf{A}^{-1} when you only know A\mathbf{A}? Use what a matrix is (P1.B5): its columns tell where e1=(1,0)\mathbf{e}_1=(1,0) and e2=(0,1)\mathbf{e}_2=(0,1) go. Undoing A\mathbf{A} must send the landing points back, so:

The first column of A−1\mathbf{A}^{-1} is the input that A\mathbf{A} sends to e1\mathbf{e}_1. The second column is the input that A\mathbf{A} sends to e2\mathbf{e}_2.

(The columns of A−1\mathbf{A}^{-1} are A−1e1\mathbf{A}^{-1}\mathbf{e}_1 and A−1e2\mathbf{A}^{-1}\mathbf{e}_2, and A\mathbf{A} undoes A−1\mathbf{A}^{-1}.) For our A\mathbf{A}, find (x,y)(x,y) with 2x−y=12x-y=1 and x+2y=0x+2y=0. The second equation gives x=−2yx=-2y, then −4y−y=1-4y-y=1, so y=−15y=-\tfrac15 and x=25x=\tfrac25. The first column of A−1\mathbf{A}^{-1} is (0.4,−0.2)(0.4,-0.2), as above, and one checks A(0.4−0.2)=(0.8+0.20.4−0.4)=(10)\mathbf{A}\binom{0.4}{-0.2}=\binom{0.8+0.2}{0.4-0.4}=\binom10. In the same way the second column, (0.2,0.4)(0.2,0.4), is the input that lands on (0,1)(0,1).

Do the same for a general A=(abcd)\mathbf{A}=\begin{pmatrix}a&b\\c&d\end{pmatrix}. The input x=1ad−bc(d−c)\mathbf{x}=\dfrac{1}{ad-bc}\binom{d}{-c} satisfies

Ax=1ad−bc(ad−bccd−dc)=(10),\mathbf{A}\mathbf{x}=\frac1{ad-bc}\binom{ad-bc}{cd-dc}=\binom10,

and 1ad−bc(−ba)\dfrac{1}{ad-bc}\binom{-b}{a} gives (01)\binom01 in the same way. Putting these two columns side by side:

(abcd)−1=1ad−bc(d−b−ca)\begin{pmatrix}a&b\\c&d\end{pmatrix}^{-1}=\frac{1}{ad-bc}\begin{pmatrix}d&-b\\-c&a\end{pmatrix}

In words: swap the two diagonal entries, change the sign of the two off-diagonal entries, and divide everything by the determinant. For our A\mathbf{A}: swap 22 and 22 (nothing changes), flip −1-1 to 11 and 11 to −1-1, divide by 55.

The division by det⁡=ad−bc\det=ad-bc has a picture. A\mathbf{A} multiplies every area by det⁡A\det\mathbf{A} (P1.B8). To undo that, A−1\mathbf{A}^{-1} must multiply every area by 1/det⁡A1/\det\mathbf{A}. For the matrix of the lesson, areas grow five times going forward and shrink to a fifth coming back.

Check with the numbers: AA−1=15(2−112)(21−12)=15(4+12−22−21+4)=(1001)\mathbf{A}\mathbf{A}^{-1}=\frac15\begin{pmatrix}2&-1\\1&2\end{pmatrix}\begin{pmatrix}2&1\\-1&2\end{pmatrix}=\frac15\begin{pmatrix}4+1&2-2\\2-2&1+4\end{pmatrix}=\begin{pmatrix}1&0\\0&1\end{pmatrix}.

This formula is a 2×22\times2 special case. For larger matrices the inverse is found by elimination (see the Go deeper box below), and in practice by a library.

When there is no inverse

Look at the projection of P1.B5 that drops every point onto the line y=xy=x:

P=(0.50.50.50.5)\mathbf{P}=\begin{pmatrix}0.5&0.5\\0.5&0.5\end{pmatrix}

It sends (3,1)(3,1) to (2,2)(2,2), and it also sends (1,3)(1,3) to (2,2)(2,2). The input (1,−1)(1,-1) goes to (0,0)(0,0), and so does (0,0)(0,0). Different inputs, same output. Given only the output (2,2)(2,2), there is no way to say whether the input was (3,1)(3,1), (1,3)(1,3) or (2,2)(2,2) itself. An inverse would have to be a rule that sends (2,2)(2,2) back to one point, so it cannot exist. The inverse widget shows it: choose Projection and the second point q\mathbf{q} lands where p\mathbf{p} does.

The formula agrees. For P\mathbf{P} we have det⁡=0.25−0.25=0\det=0.25-0.25=0, and 1ad−bc\frac{1}{ad-bc} would be a division by zero. The formula is not failing; it is telling you that there is nothing to find.

This is exactly the situation of P1.B7 and P1.B8. A non-zero vector n\mathbf{n} with Pn=0\mathbf{P}\mathbf{n}=\mathbf{0} (here n=(1,−1)\mathbf{n}=(1,-1)) is in the null space. Then P(x+n)=Px\mathbf{P}(\mathbf{x}+\mathbf{n})=\mathbf{P}\mathbf{x} for every x\mathbf{x}, so each output comes from a whole line of inputs. A square matrix has an inverse exactly when this never happens, and then every output is reached too. The whole picture fits in one statement:

Two clarifications. First, singular does not mean small or zero: (1224)\begin{pmatrix}1&2\\2&4\end{pmatrix} has no zero entry, and 0.1 I0.1\,\mathbf{I} is tiny but has the inverse 10 I10\,\mathbf{I} (P1.B8). Second, “different inputs give different outputs” and “every output is reached” are two separate things, and an inverse needs both. For a square matrix each one implies the other, which is why a single number, the determinant, decides everything. For matrices that are not square, they come apart.

Go deeper If a square matrix undoes A on one side, it undoes it on the other

The definition asks for both BA=I\mathbf{B}\mathbf{A}=\mathbf{I} and AB=I\mathbf{A}\mathbf{B}=\mathbf{I}. For square matrices one is enough. Suppose BA=I\mathbf{B}\mathbf{A}=\mathbf{I}. If Ax=0\mathbf{A}\mathbf{x}=\mathbf{0} then x=BAx=B0=0\mathbf{x}=\mathbf{B}\mathbf{A}\mathbf{x}=\mathbf{B}\mathbf{0}=\mathbf{0}, so the null space is just 0\mathbf{0} and the columns of the square matrix A\mathbf{A} are independent. nn independent vectors in Rn\mathbb{R}^n span the whole space (P1.B7), so for each ej\mathbf{e}_j there is a cj\mathbf{c}_j with Acj=ej\mathbf{A}\mathbf{c}_j=\mathbf{e}_j; put these as the columns of a matrix C\mathbf{C}, so that AC=I\mathbf{A}\mathbf{C}=\mathbf{I}. Then B=B(AC)=(BA)C=C\mathbf{B}=\mathbf{B}(\mathbf{A}\mathbf{C})=(\mathbf{B}\mathbf{A})\mathbf{C}=\mathbf{C}, and B\mathbf{B} is a two-sided inverse.

Only square matrices have an inverse

If A\mathbf{A} is m×nm\times n it turns nn numbers into mm numbers, and its inverse would have to turn the mm numbers back into the nn. A two-sided inverse needs m=nm=n. For a tall matrix (m>nm>n, more outputs than inputs) the output is a flat sheet inside a bigger space, so most points of the big space are not outputs of anything. For a wide matrix (m<nm<n) some information must be lost, so different inputs share outputs (P1.B7: rank at most min⁡(m,n)\min(m,n), so the null space is not just 0\mathbf{0}). Such a matrix cannot have a two-sided inverse, and the three equivalent statements above are about square matrices.

Go deeper Left and right inverses of tall and wide matrices

A tall matrix with independent columns can still be undone from one side. Take A3=(100111)\mathbf{A}_3=\begin{pmatrix}1&0\\0&1\\1&1\end{pmatrix} (columns (1,0,1)(1,0,1) and (0,1,1)(0,1,1) from P1.B7) and

L=13(2−11−121).\mathbf{L}=\frac13\begin{pmatrix}2&-1&1\\-1&2&1\end{pmatrix}.

Then LA3=I2\mathbf{L}\mathbf{A}_3=\mathbf{I}_2: L\mathbf{L} recovers the two input numbers from the three output numbers. But A3L\mathbf{A}_3\mathbf{L} is 3×33\times3 with rank at most 22, so it cannot be I3\mathbf{I}_3. L\mathbf{L} is a left inverse. It is not unique: (100010)\begin{pmatrix}1&0&0\\0&1&0\end{pmatrix} is another one. The particular L\mathbf{L} above is the pseudo-inverse of A3\mathbf{A}_3, which P1.B13 explains. A wide matrix with independent rows can have right inverses (AR=I\mathbf{A}\mathbf{R}=\mathbf{I}) in the same way. In this course we need the pseudo-inverse only as a name.

Rules for inverses

Assume all the matrices below are square and invertible.

RuleIn words
(AB)−1=B−1A−1(\mathbf{A}\mathbf{B})^{-1}=\mathbf{B}^{-1}\mathbf{A}^{-1}undo the last step first
(A⊤)−1=(A−1)⊤(\mathbf{A}^\top)^{-1}=(\mathbf{A}^{-1})^\toptransposing and inverting can be done in either order
(cA)−1=1cA−1(c\mathbf{A})^{-1}=\tfrac1c\mathbf{A}^{-1} for a number c≠0c\ne0scaling by cc is undone by scaling by 1/c1/c
(A−1)−1=A(\mathbf{A}^{-1})^{-1}=\mathbf{A}undoing the undo gives the original
det⁡A−1=1/det⁡A\det\mathbf{A}^{-1}=1/\det\mathbf{A}from the last section

The first rule is the one to understand. If AB\mathbf{A}\mathbf{B} means “first B\mathbf{B}, then A\mathbf{A}” (P1.B6), then to undo it you must undo A\mathbf{A} first and then B\mathbf{B}. You put on socks, then shoes; to undo that, you take off the shoes first, then the socks. In symbols, multiply AB\mathbf{A}\mathbf{B} by the claimed inverse:

(AB)(B−1A−1)=A(BB−1)A−1=AIA−1=AA−1=I.\begin{aligned} (\mathbf{A}\mathbf{B})(\mathbf{B}^{-1}\mathbf{A}^{-1})&=\mathbf{A}(\mathbf{B}\mathbf{B}^{-1})\mathbf{A}^{-1}\\ &=\mathbf{A}\mathbf{I}\mathbf{A}^{-1}\\ &=\mathbf{A}\mathbf{A}^{-1}=\mathbf{I}. \end{aligned}

The inside pair cancels first, which is why the order has to be reversed. Take A\mathbf{A} as above and B=(2013)\mathbf{B}=\begin{pmatrix}2&0\\1&3\end{pmatrix} from P1.B8, with det⁡B=6\det\mathbf{B}=6 and B−1=16(30−12)\mathbf{B}^{-1}=\frac16\begin{pmatrix}3&0\\-1&2\end{pmatrix}. Then AB=(3−346)\mathbf{A}\mathbf{B}=\begin{pmatrix}3&-3\\4&6\end{pmatrix} has det⁡=30\det=30, so (AB)−1=130(63−43)(\mathbf{A}\mathbf{B})^{-1}=\frac1{30}\begin{pmatrix}6&3\\-4&3\end{pmatrix} by the formula. And

B−1A−1=16(30−12)⋅15(21−12)=130(63−43),\begin{gathered} \mathbf{B}^{-1}\mathbf{A}^{-1} \\ \quad=\frac16\begin{pmatrix}3&0\\-1&2\end{pmatrix}\cdot\frac15\begin{pmatrix}2&1\\-1&2\end{pmatrix} \\ \quad=\frac1{30}\begin{pmatrix}6&3\\-4&3\end{pmatrix}, \end{gathered}

the same matrix. The wrong order gives A−1B−1=130(52−54)\mathbf{A}^{-1}\mathbf{B}^{-1}=\frac1{30}\begin{pmatrix}5&2\\-5&4\end{pmatrix}, which is a different matrix. For three matrices, (ABC)−1=C−1B−1A−1(\mathbf{A}\mathbf{B}\mathbf{C})^{-1}=\mathbf{C}^{-1}\mathbf{B}^{-1}\mathbf{A}^{-1}. Also, for square matrices, a product is invertible exactly when every factor is: if one factor squashes the plane, the product does too.

The other rules check out on A\mathbf{A}. The transpose is A⊤=(21−12)\mathbf{A}^\top=\begin{pmatrix}2&1\\-1&2\end{pmatrix}, whose inverse is 15(2−112)\frac15\begin{pmatrix}2&-1\\1&2\end{pmatrix}, which is (A−1)⊤(\mathbf{A}^{-1})^\top. For 3A=(6−336)3\mathbf{A}=\begin{pmatrix}6&-3\\3&6\end{pmatrix}, det⁡=45\det=45, the inverse is 145(63−36)=13A−1\frac1{45}\begin{pmatrix}6&3\\-3&6\end{pmatrix}=\frac13\mathbf{A}^{-1}. (The transpose rule is stated here and explained in P1.B10.)

What is not a rule. There is no simple sum or product rule for (A+B)−1(\mathbf{A}+\mathbf{B})^{-1}, and certainly (A+B)−1≠A−1+B−1(\mathbf{A}+\mathbf{B})^{-1}\ne\mathbf{A}^{-1}+\mathbf{B}^{-1}: (I+I)−1=(2I)−1=0.5 I(\mathbf{I}+\mathbf{I})^{-1}=(2\mathbf{I})^{-1}=0.5\,\mathbf{I}, but I−1+I−1=2I\mathbf{I}^{-1}+\mathbf{I}^{-1}=2\mathbf{I}. Also A−1\mathbf{A}^{-1} is not the matrix of reciprocals 1/Aij1/A_{ij}. For our A\mathbf{A} the reciprocals are (0.5−110.5)\begin{pmatrix}0.5&-1\\1&0.5\end{pmatrix}, which is not the inverse. For a diagonal matrix, though, the inverse is found by taking reciprocals of the diagonal entries, as the next table shows.

Inverses you can write down at once

MatrixInverse, and why
Identity I\mathbf{I}I\mathbf{I}: it does nothing
Diagonal diag⁡(d1,…,dn)\operatorname{diag}(d_1,\dots,d_n) with every di≠0d_i\ne0diag⁡(1/d1,…,1/dn)\operatorname{diag}(1/d_1,\dots,1/d_n): a coordinate stretched by did_i is stretched back by 1/di1/d_i. With a 00 on the diagonal that coordinate is flattened and there is no inverse.
Scaling every direction by c≠0c\ne0, that is cIc\mathbf{I}1cI\frac1c\mathbf{I} (a special diagonal matrix)
Rotation by an angle θ\thetathe rotation by −θ-\theta: turn back by the same angle. It also equals the transpose; P1.B10 explains why and makes it a general rule for orthogonal matrices.
Shear (1k01)\begin{pmatrix}1&k\\0&1\end{pmatrix}(1−k01)\begin{pmatrix}1&-k\\0&1\end{pmatrix}: slide back by the same amount
Reflection (−1001)\begin{pmatrix}-1&0\\0&1\end{pmatrix} or the swap (0110)\begin{pmatrix}0&1\\1&0\end{pmatrix}itself: doing it twice gives the identity
Projection onto a linenone: many points land on one

For example diag⁡(2,0.5)−1=diag⁡(0.5,2)\operatorname{diag}(2,0.5)^{-1}=\operatorname{diag}(0.5,2), and the rotation by 30∘30^\circ is undone by the rotation by −30∘-30^\circ, whose matrix is the transpose. You saw each of these in the inverse widget.

Cancelling is allowed now

P1.B6 showed that AB=AC\mathbf{A}\mathbf{B}=\mathbf{A}\mathbf{C} does not give B=C\mathbf{B}=\mathbf{C} when A\mathbf{A} squashes the plane. If A\mathbf{A} is invertible, it does: multiply both sides from the left by A−1\mathbf{A}^{-1} to get B=C\mathbf{B}=\mathbf{C}. The side matters, because matrices do not commute:

  • AX=B\mathbf{A}\mathbf{X}=\mathbf{B} gives X=A−1B\mathbf{X}=\mathbf{A}^{-1}\mathbf{B} (multiply on the left of both sides);
  • XA=B\mathbf{X}\mathbf{A}=\mathbf{B} gives X=BA−1\mathbf{X}=\mathbf{B}\mathbf{A}^{-1} (multiply on the right of both sides).

Never write B/A\mathbf{B}/\mathbf{A}: it would not say which of these you mean.

Linear systems: Ax=b\mathbf{A}\mathbf{x}=\mathbf{b}

A linear system is a set of equations in unknowns x1,x2,…x_1,x_2,\dots where each unknown only appears multiplied by a number and added up. Take the system

2x1−x2=1x1+2x2=3\begin{aligned} 2x_1-x_2&=1\\ x_1+2x_2&=3 \end{aligned}

In matrix form this is

(2−112)(x1x2)=(13)\begin{pmatrix}2&-1\\1&2\end{pmatrix}\binom{x_1}{x_2}=\binom13

which we write as Ax=b\mathbf{A}\mathbf{x}=\mathbf{b}. Here A\mathbf{A} and b\mathbf{b} are known and we look for x\mathbf{x}. There are three ways to read this one equation, and each of the three pictures is useful:

  1. Row view: lines that meet. Each equation is a line in the (x1,x2)(x_1,x_2) plane: 2x1−x2=12x_1-x_2=1 is one line and x1+2x2=3x_1+2x_2=3 another. A solution is a point on both lines. (In 3-D each equation is a plane, and in nn dimensions a flat slice; a solution lies on all of them.)
  2. Column view: a combination of the columns. Because Ax=x1 a1+x2 a2\mathbf{A}\mathbf{x}=x_1\,\mathbf{a}_1+x_2\,\mathbf{a}_2 (P1.B5), the system asks: how much of column 1 and how much of column 2 must be added to make b\mathbf{b}? Here 1⋅(2,1)+1⋅(−1,2)=(1,3)1\cdot(2,1)+1\cdot(-1,2)=(1,3), so x1=x2=1x_1=x_2=1.
  3. Transformation view: find the input. Which input does A\mathbf{A} send to b\mathbf{b}? If A\mathbf{A} can be undone, apply the undo: x=A−1b=15(21−12)(13)=15(55)=(11)\mathbf{x}=\mathbf{A}^{-1}\mathbf{b}=\frac15\begin{pmatrix}2&1\\-1&2\end{pmatrix}\binom13=\frac15\binom55=\binom11.

All three give the same answer, x=(1,1)\mathbf{x}=(1,1), and the system-lines widget draws the first two at once.

One system, two pictures: lines that cross, columns that add up to b

Row view: each equation is a line

−3−2−1123−3−2−1123x₁x₂row 1row 2solution

Column view: b as a combination of the columns

−3−2−1123−3−2−1123col 1col 2b
2x₁ − x₂ = 1 and x₁ + 2x₂ = 3
det A = 5
rank A = 2, rank of [A | b] = 2
Solution: x = (1, 1)
Condition number of A (largest stretch ÷ smallest stretch): 1

One solution: x₁ = 1, x₂ = 1. The two lines cross at exactly one point, and exactly one combination of the columns gives b (det = 5, so A can be undone).

Row view: line 1 is blue, line 2 is pink, and the green dot is the solution. When both lines are the same, the pink line is drawn under the blue one. Column view: the arrows are column 1 and column 2 of A, the ring is the target b, and the thin arrows show the combination x₁ × column 1, then x₂ × column 2, that arrives at b. When the columns lie on one line, the dashed line is everything A x can reach. Entries are shown rounded to 3 decimals.

System lines. Left, the row view: each equation is a line, line 1 in blue and line 2 in pink, and the green dot is the solution. Right, the column view: the arrows are column 1 (blue) and column 2 (pink) of A, the ring is b, and the thin dashed arrows add x₁ times column 1 and then x₂ times column 2 to arrive at b. The six sliders edit A and b. The readouts show the equations, the determinant, the ranks of A and of [A | b], the solutions and the condition number, and the status says whether there is one solution, none, or infinitely many.

Things to try:

  1. At the start, the lines cross at (1,1)(1,1) and the thin arrows go once along column 1 and then once along column 2, and land on b=(1,3)\mathbf{b}=(1,3). The status says there is one solution.
  2. Press Parallel lines (the matrix (1224)\begin{pmatrix}1&2\\2&4\end{pmatrix} with b=(1,0)\mathbf{b}=(1,0)). The lines never meet. In the column view both columns lie on one dashed line through the origin, and b\mathbf{b} is off that line: no combination of the columns reaches it. The status says there is no solution.
  3. Press Same line (the same matrix with b=(3,6)\mathbf{b}=(3,6)). Now the two equations are the same line, drawn on top of each other, and b\mathbf{b} is on the dashed line. Every point of the line is a solution: infinitely many.
  4. Press A row of zeros. The second equation reads 0x1+0x2=10x_1+0x_2=1, which is impossible. Change b2b_2 to 00 and it reads 0=00=0, which says nothing, and the first equation alone leaves a whole line of solutions.
  5. Press Nearly parallel (the matrix (1111.02)\begin{pmatrix}1&1\\1&1.02\end{pmatrix} with b=(2,2.02)\mathbf{b}=(2,2.02)). The lines meet at (1,1)(1,1), but at a tiny angle. Now move b2b_2 from 2.022.02 to 2.032.03: the crossing point jumps to (0.5,1.5)(0.5,1.5), a big move for a change of 0.010.01.

Intuition

Think of A\mathbf{A} as a machine that takes a recipe x\mathbf{x} (how much of each ingredient) and produces a result b\mathbf{b}. Solving Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} means: given the result, find the recipe. If the machine loses nothing, there is exactly one recipe. If it squashes, there may be many recipes for one result, or results that no recipe makes.

Math

The system Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} has a solution exactly when b\mathbf{b} is in the column space of A\mathbf{A} (P1.B7). If A\mathbf{A} is square and invertible, the solution is unique and equals A−1b\mathbf{A}^{-1}\mathbf{b}: multiply both sides on the left by A−1\mathbf{A}^{-1} to get x=A−1b\mathbf{x}=\mathbf{A}^{-1}\mathbf{b}, and substitute back to see it works. Uniqueness: two solutions differ by a vector in the null space, which is 0\mathbf{0}.

Code

import numpy as np

A = np.array([[2.0, -1.0], [1.0, 2.0]])
b = np.array([1.0, 3.0])
x = np.linalg.solve(A, b)
print(x)        # [1. 1.]

np.linalg.solve(A, b) finds x\mathbf{x} directly, without building A−1\mathbf{A}^{-1}. More on this below.

One solution, none, or infinitely many

A system of two equations in two unknowns has exactly three possible outcomes, and the pictures show which:

  • One solution. Row view: the lines cross at one point. Column view: the columns point in different directions, so they reach every b\mathbf{b}, in exactly one way. Algebra: det⁡≠0\det\ne0 and rank 22.
  • No solution. Row view: parallel lines that never meet. Column view: the columns lie on one line and b\mathbf{b} is off that line. Algebra: det⁡=0\det=0 and b\mathbf{b} is not in the column space.
  • Infinitely many solutions. Row view: the two equations are the same line. Column view: the columns lie on one line and b\mathbf{b} is on it. Algebra: det⁡=0\det=0 and b\mathbf{b} is in the column space.

Notice what decides the case. When det⁡≠0\det\ne0, the column space is the whole plane (P1.B7), so b\mathbf{b} is always in it and the answer is “one solution” for every b\mathbf{b}. When det⁡=0\det=0, the column space is only a line (or a point), and then it depends on b\mathbf{b}: on the line gives infinitely many, off the line gives none. It is never exactly two or three solutions. The usual rank statement of this (stated here, standard in any linear algebra text): Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} has a solution exactly when rank⁡A=rank⁡[A ∣ b]\operatorname{rank}\mathbf{A}=\operatorname{rank}[\mathbf{A}\,|\,\mathbf{b}] (adding the column b\mathbf{b} does not add a new direction), and the solution is unique when that rank also equals the number of unknowns. The system-lines widget prints both ranks.

The example of P1.B7. For A=(1224)\mathbf{A}=\begin{pmatrix}1&2\\2&4\end{pmatrix} (column 2 is twice column 1), the column space is the line y=2xy=2x. The vector b=(3,6)\mathbf{b}=(3,6) is on it: x=(1,1)\mathbf{x}=(1,1) works, since 1⋅(1,2)+1⋅(2,4)=(3,6)1\cdot(1,2)+1\cdot(2,4)=(3,6). The vector b=(1,0)\mathbf{b}=(1,0) is off it: there is no solution.

All the solutions, when there are many. If xp\mathbf{x}_p is one solution and n\mathbf{n} is in the null space (P1.B7), then A(xp+n)=b+0=b\mathbf{A}(\mathbf{x}_p+\mathbf{n})=\mathbf{b}+\mathbf{0}=\mathbf{b}. Conversely two solutions differ by a null-space vector. So the full set of solutions is xp\mathbf{x}_p plus the null space. For the example, n=(−2,1)\mathbf{n}=(-2,1) spans the null space (1⋅(−2)+2⋅1=01\cdot(-2)+2\cdot1=0 and 2⋅(−2)+4⋅1=02\cdot(-2)+4\cdot1=0), and the solutions of Ax=(3,6)\mathbf{A}\mathbf{x}=(3,6) are

x=(11)+t(−21),\mathbf{x}=\binom11+t\binom{-2}{1},

for any number tt. This is the line x1+2x2=3x_1+2x_2=3, which is exactly the line in the row view. The special system Ax=0\mathbf{A}\mathbf{x}=\mathbf{0} always has the solution x=0\mathbf{x}=\mathbf{0}; it has other solutions exactly when the null space is bigger than 0\mathbf{0}, which for a square matrix means det⁡=0\det=0.

Systems that are not square. With more equations than unknowns (a tall matrix) there is usually no solution, because many conditions have to hold at once; that is the situation of fitting a line to many data points, and the closest we can get is the job of least squares (P1.B11, P3.A2). With fewer equations than unknowns (a wide matrix) there are usually infinitely many solutions, or none. In 3-D with three equations each equation is a plane: three planes usually meet at one point, but they can also share a line (infinitely many solutions) or have no common point at all, for example when two are parallel or when each pair meets in a line and the three lines run side by side like the edges of a prism (no solution).

Solving by elimination

Computers do not find A−1\mathbf{A}^{-1} first. They use the row operations of P1.B8: you may swap two equations, multiply an equation by a number, and add a multiple of one equation to another, and the solutions do not change. The plan is to use them to reach a triangular system, whose last equation has one unknown, and then work upwards (back substitution). Carry b\mathbf{b} along as an extra column: the augmented matrix [A ∣ b][\mathbf{A}\,|\,\mathbf{b}].

For 2x1−x2=12x_1-x_2=1, x1+2x2=3x_1+2x_2=3:

(2−11123)→R2−12R1 (2−1102.52.5)\begin{aligned} &\left(\begin{array}{cc|c}2&-1&1\\1&2&3\end{array}\right)\\[2pt] \xrightarrow{R_2-\frac12R_1}\ &\left(\begin{array}{cc|c}2&-1&1\\0&2.5&2.5\end{array}\right) \end{aligned}

The second row now says 2.5 x2=2.52.5\,x_2=2.5, so x2=1x_2=1. The first row says 2x1−1=12x_1-1=1, so x1=1x_1=1. The first non-zero entry of each row (22 and 2.52.5) is a pivot, the number you divide by.

A 3×33\times3 example with the matrix M\mathbf{M} from P1.B8 and b=(7,19,49)\mathbf{b}=(7,19,49):

(21174331987949)→ (2117011503521)→ (211701150026)\begin{aligned} &\left(\begin{array}{ccc|c}2&1&1&7\\4&3&3&19\\8&7&9&49\end{array}\right)\\[2pt] \to\ &\left(\begin{array}{ccc|c}2&1&1&7\\0&1&1&5\\0&3&5&21\end{array}\right)\\[2pt] \to\ &\left(\begin{array}{ccc|c}2&1&1&7\\0&1&1&5\\0&0&2&6\end{array}\right) \end{aligned}

(first R2−2R1R_2-2R_1 and R3−4R1R_3-4R_1, then R3−3R2R_3-3R_2; these are the same steps as in P1.B8, now also applied to b\mathbf{b}). Back substitution: 2z=62z=6 gives z=3z=3; then y+3=5y+3=5 gives y=2y=2; then 2x+2+3=72x+2+3=7 gives x=1x=1. The solution is (1,2,3)(1,2,3). The pivots 2,1,22,1,2 are the ones whose product gave det⁡M=4\det\mathbf{M}=4 in P1.B8: the same elimination both solves the system and computes the determinant.

When things go wrong, elimination tells you which case you are in:

  • A pivot position holds a 00. Swap with a row below that has a non-zero entry. For (0111)x=(23)\begin{pmatrix}0&1\\1&1\end{pmatrix}\mathbf{x}=\binom23, swapping the two rows gives x1+x2=3x_1+x_2=3 and x2=2x_2=2, so x=(1,2)\mathbf{x}=(1,2). (Computers swap even when the pivot is not zero: they move the largest available entry of the column into the pivot position, because dividing by a small pivot magnifies rounding errors.)
  • A row becomes all zeros on the left. Look at its right side. For (1224)\begin{pmatrix}1&2\\2&4\end{pmatrix} and b=(3,6)\mathbf{b}=(3,6), R2−2R1R_2-2R_1 gives (123000)\left(\begin{array}{cc|c}1&2&3\\0&0&0\end{array}\right): the last row reads 0=00=0, which is always true and adds no information. One equation for two unknowns: x2x_2 is free and each choice gives a solution (infinitely many). For b=(1,0)\mathbf{b}=(1,0), R2−2R1R_2-2R_1 gives (12100−2)\left(\begin{array}{cc|c}1&2&1\\0&0&-2\end{array}\right): the last row reads 0=−20=-2, which is never true. No solution.
  • The number of pivots is the rank of A\mathbf{A} (P1.B7). A square system has exactly one solution when there are nn pivots.

Cost. Elimination takes a number of steps that grows like n3n^3 (about n3/3n^3/3 multiplications, as the next section says) and back substitution only about n2n^2. If you have many right-hand sides for the same A\mathbf{A}, the elimination part can be kept and reused.

Go deeper Finding the whole inverse by elimination

The inverse itself can be found with elimination: write A\mathbf{A} next to the identity and row-reduce until the left half becomes I\mathbf{I}. The right half is then A−1\mathbf{A}^{-1}. (Solving Ax=ej\mathbf{A}\mathbf{x}=\mathbf{e}_j for each column of I\mathbf{I} at once, which is exactly the first-columns idea above.) For our A\mathbf{A}:

(2−1101201)→R2−12R1(2−11002.5−0.51)→R2÷2.5(2−11001−0.20.4)→R1+R2(200.80.401−0.20.4)→R1÷2(100.40.201−0.20.4)\begin{aligned} &\left(\begin{array}{cc|cc}2&-1&1&0\\1&2&0&1\end{array}\right)\\[2pt] \xrightarrow{R_2-\frac12R_1}&\left(\begin{array}{cc|cc}2&-1&1&0\\0&2.5&-0.5&1\end{array}\right)\\[2pt] \xrightarrow{R_2\div2.5}&\left(\begin{array}{cc|cc}2&-1&1&0\\0&1&-0.2&0.4\end{array}\right)\\[2pt] \xrightarrow{R_1+R_2}&\left(\begin{array}{cc|cc}2&0&0.8&0.4\\0&1&-0.2&0.4\end{array}\right)\\[2pt] \xrightarrow{R_1\div2}&\left(\begin{array}{cc|cc}1&0&0.4&0.2\\0&1&-0.2&0.4\end{array}\right) \end{aligned}

The right half is (0.40.2−0.20.4)=A−1\begin{pmatrix}0.4&0.2\\-0.2&0.4\end{pmatrix}=\mathbf{A}^{-1}. If a pivot cannot be found, no inverse exists, which agrees with the list of equivalent statements.

Go deeper LU factorization: remember the elimination

The steps of elimination can be recorded as a matrix. For our A\mathbf{A}, one step (R2−12R1R_2-\tfrac12R_1) produced the triangular matrix U=(2−102.5)\mathbf{U}=\begin{pmatrix}2&-1\\0&2.5\end{pmatrix}. The step is stored in L=(100.51)\mathbf{L}=\begin{pmatrix}1&0\\0.5&1\end{pmatrix} (the multiplier 12\tfrac12 goes below the diagonal), and indeed LU=(2−112)=A\mathbf{L}\mathbf{U}=\begin{pmatrix}2&-1\\1&2\end{pmatrix}=\mathbf{A}. Solving Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} is then two easy triangular solves: Ly=b\mathbf{L}\mathbf{y}=\mathbf{b} (going down), then Ux=y\mathbf{U}\mathbf{x}=\mathbf{y} (going up). The expensive part, finding L\mathbf{L} and U\mathbf{U}, is done once and reused for every new b\mathbf{b}. With row swaps it is called LU factorization with pivoting, and it is what NumPy and most libraries use.

Solve, do not invert

Since x=A−1b\mathbf{x}=\mathbf{A}^{-1}\mathbf{b}, it is tempting to write np.linalg.inv(A) @ b. Numerical programmers advise against it. In maths, “A−1b\mathbf{A}^{-1}\mathbf{b}” is the right way to write the answer; in code, it should mean “solve Ax=b\mathbf{A}\mathbf{x}=\mathbf{b}”. There are three reasons.

  1. It takes more work. An LU solve needs about n3/3n^3/3 multiplications for a dense n×nn\times n matrix, while building the whole inverse needs about n3n^3, around three times more (the usual textbook counts). You then still have to multiply by b\mathbf{b}.
  2. It is usually less accurate. The inverse is a big matrix with its own rounding errors, and multiplying by it adds more. A solve works on the equations directly. The second NumPy cell below shows it on a famously difficult matrix.
  3. It throws away structure. The inverse of a sparse matrix (mostly zeros) is usually dense, so you give up memory and speed that a solver would keep. And you almost never need the inverse itself, only its effect on one or a few vectors.

np.linalg.solve(A, b) calls the LAPACK routine gesv, which is an LU factorization with row swaps. If you have several right-hand sides, pass them as the columns of a matrix, and the factorization is done once.

In the mathsIn the code
x=A−1b\mathbf{x}=\mathbf{A}^{-1}\mathbf{b}np.linalg.solve(A, b)
X=A−1B\mathbf{X}=\mathbf{A}^{-1}\mathbf{B}np.linalg.solve(A, B)
w=(X⊤X)−1X⊤y\mathbf{w}=(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y} (P3.A2)np.linalg.solve(X.T @ X, X.T @ y), or a least-squares routine (P1.B11)

The only time to form an inverse is when you really need its entries, for example to read off a covariance-like quantity, and even then it should be a conscious choice.

When answers are fragile

Some systems are solvable and unique but badly behaved. P1.B7 met one: the basis (1,0)(1,0) and (1,0.001)(1,0.001) needs weights −997-997 and 10001000 to reach the modest point (3,1)(3,1). As a system:

(1100.001)(x1x2)=(31)\begin{pmatrix}1&1\\0&0.001\end{pmatrix}\binom{x_1}{x_2}=\binom31

has the solution x=(−997,1000)\mathbf{x}=(-997,1000).

Change the target to b=(2,0)\mathbf{b}=(2,0) and the answer is x=(2,0)\mathbf{x}=(2,0). Nudge b2b_2 by only 0.0010.001, to b=(2,0.001)\mathbf{b}=(2,0.001), and the answer becomes x=(1,1)\mathbf{x}=(1,1). The target moved by 0.05%0.05\% of its size and the answer moved by about 71%71\%. The reason is in the inverse: (1100.001)−1=(1−100001000)\begin{pmatrix}1&1\\0&0.001\end{pmatrix}^{-1}=\begin{pmatrix}1&-1000\\0&1000\end{pmatrix}, which multiplies any error in b2b_2 by 10001000.

The condition number (previewed in P1.B8) measures this. It is the largest stretch of the matrix divided by the smallest. For this matrix it is about 20002000. A rule of thumb, with proof in the Go deeper box: an error in b\mathbf{b} can be magnified in x\mathbf{x} by up to about the condition number (measured as relative errors). The “up to” is real: some errors are magnified fully and some are not. A matrix with condition number 11, like our rotation-and-scale A\mathbf{A}, never magnifies anything. A matrix that is exactly singular has condition number ∞\infty.

In the system-lines widget, press Nearly parallel. In the row view the two lines nearly coincide, so a small shove of one line slides the crossing point a long way. In the inverse widget the Nearly squashed preset shows the same thing from the other side: the inverse exists, but its entries are 5151 and −50-50 and its condition number is about 202202.

Some consequences:

  • Digits. Floating-point numbers carry about 16 significant digits (P1.B7 and P1.B8 met their rounding). As a rule of thumb, a condition number near 10k10^k leaves you with roughly 16−k16-k trustworthy digits. At 101610^{16} you cannot trust any digit.
  • It is the problem, not the method. Rounding errors in the data are unavoidable, and a badly conditioned system turns them into big errors in the answer, whichever method you use. A better algorithm avoids adding more error, but it cannot make the data more informative.
  • Singular versus nearly singular. On a computer, a matrix that is singular on paper may look slightly non-singular after rounding, and one that is nearly singular may look fine. So never test det⁡=0\det=0 exactly; look at the rank with a tolerance (P1.B7) or at the condition number, np.linalg.cond.
  • In machine learning, features that are nearly copies of each other give a nearly singular matrix, and the learned weights swing wildly with tiny changes in the data. This is why regression with correlated features is unstable (P3.A2) and why regularization helps (P3.A6).
Go deeper Why the condition number bounds the error

Let Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} and perturb the right side to b+δb\mathbf{b}+\delta\mathbf{b}, with solution x+δx\mathbf{x}+\delta\mathbf{x}. Subtracting the equations gives A δx=δb\mathbf{A}\,\delta\mathbf{x}=\delta\mathbf{b}, so δx=A−1δb\delta\mathbf{x}=\mathbf{A}^{-1}\delta\mathbf{b}. The largest stretch of A−1\mathbf{A}^{-1} is one over the smallest stretch of A\mathbf{A}, so ∥δx∥≤∥δb∥/smin⁡\lVert\delta\mathbf{x}\rVert\le\lVert\delta\mathbf{b}\rVert/s_{\min} where smin⁡s_{\min} is the smallest stretch of A\mathbf{A}. Also ∥b∥=∥Ax∥≤smax⁡∥x∥\lVert\mathbf{b}\rVert=\lVert\mathbf{A}\mathbf{x}\rVert\le s_{\max}\lVert\mathbf{x}\rVert with smax⁡s_{\max} the largest stretch. The second inequality gives a lower bound on ∥x∥\|\mathbf{x}\|, so dividing the first by ∥x∥\|\mathbf{x}\| and using that bound gives

∥δx∥∥x∥≤smax⁡smin⁡⋅∥δb∥∥b∥.\frac{\lVert\delta\mathbf{x}\rVert}{\lVert\mathbf{x}\rVert}\le\frac{s_{\max}}{s_{\min}}\cdot\frac{\lVert\delta\mathbf{b}\rVert}{\lVert\mathbf{b}\rVert}.

The ratio smax⁡/smin⁡s_{\max}/s_{\min} is the condition number. (Here “stretch” means the factor by which a vector’s length changes at most or at least; the exact definition by singular values is in P1.B13.) The bound is reached when δb\delta\mathbf{b} points along the direction that A−1\mathbf{A}^{-1} stretches most and x\mathbf{x} along the one that A\mathbf{A} stretches most.

Inverses and systems in NumPy

np.linalg.inv(A) returns the inverse, np.linalg.solve(A, b) solves the system, A @ B multiplies, and np.linalg.cond(A) gives the condition number. The first cell goes through the lesson: the inverse and its check, solving 2×22\times2 and 3×33\times3 systems, several right-hand sides at once, and what happens for a singular matrix.

Try it: inverse, solve and a singular matrix

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What to expect:

  • Check an inverse with np.allclose, not ==. The product HH−1\mathbf{H}\mathbf{H}^{-1} is the identity only up to rounding, and an exact comparison can fail even though the answer is right. On the machine where this lesson was checked, == gave False for H=(1234)\mathbf{H}=\begin{pmatrix}1&2\\3&4\end{pmatrix} (the bottom-left entry came out as about 9×10−169\times10^{-16} instead of 00) while np.allclose gave True. Your last digits may differ; the point is to never rely on exact equality of floating-point results (P1.B7 and P1.B8 made the same point about ranks and determinants).
  • solve takes a vector or a matrix. With a matrix on the right, each column is a separate system. Here the columns (1,3)(1,3) and (5,5)(5,5) give the solutions (1,1)(1,1) and (3,1)(3,1), which come back as the columns of the result.
  • A singular matrix raises an error. Without the try, the last line of the error message reads numpy.linalg.LinAlgError: Singular matrix. The exact wording and the class name path can differ between NumPy versions. np.linalg.solve(S, b) raises the same error. NumPy raises it when elimination meets an exact zero pivot, as for S\mathbf{S} here.
  • A nearly singular matrix usually does not raise an error. N differs from S\mathbf{S} in one entry by 10−710^{-7}, so it is not singular, and NumPy happily returns an inverse with entries of size 4×1074\times10^{7} and a condition number of about 2.5×1082.5\times10^8. A singular-on-paper matrix whose rounding leaves a tiny pivot can also fail to raise (P1.B8 met this with its integer matrix S\mathbf{S}). So no error does not mean the answer is trustworthy: look at np.linalg.cond.

The second cell compares solve and inv on the 10×1010\times10 Hilbert matrix, whose entries are 1/(i+j+1)1/(i+j+1) and which is a famous badly conditioned matrix, and then repeats the nearly parallel system from the last section.

Try it: solve versus inverse, and fragile answers

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What to expect (the exact digits depend on the machine, the pattern does not usually):

  • The condition number of H\mathbf{H} is about 1.6×10131.6\times10^{13}, so we expect to lose about 13 of the 16 digits. On the machine where this lesson was checked, the residual ∣Hx−b∣\lvert\mathbf{H}\mathbf{x}-\mathbf{b}\rvert of solve was about 4×10−164\times10^{-16} (it satisfies the equations to rounding), while the residual of inv(H) @ b was about 2×10−52\times10^{-5}.
  • The error in x\mathbf{x} is much larger than the residual for both, about 2×10−42\times10^{-4} for solve and 6×10−36\times10^{-3} for inv. That large error is the condition number at work, and no method could avoid it. But the inverse adds extra error on top, as the text said.
  • The three solves of the nearly parallel system print (−997,1000)(-997,1000), (2,0)(2,0) and (1,1)(1,1), the numbers from the last section, and the condition number rounds to 20002000.

Where you will meet it next

  • Linear regression (P3.A2). Fitting a line or a plane by least squares leads to the normal equations X⊤Xw=X⊤y\mathbf{X}^\top\mathbf{X}\mathbf{w}=\mathbf{X}^\top\mathbf{y} (derived in P1.B11 and P3.A2), a linear system for the weights w\mathbf{w}. You solve it with np.linalg.solve, not by inverting X⊤X\mathbf{X}^\top\mathbf{X}. If one feature is a copy of another, X⊤X\mathbf{X}^\top\mathbf{X} is singular and there is no single best w\mathbf{w} (infinitely many solutions, as in this lesson). For instance X=(122436)\mathbf{X}=\begin{pmatrix}1&2\\2&4\\3&6\end{pmatrix} has the second column equal to twice the first, and X⊤X=(14282856)\mathbf{X}^\top\mathbf{X}=\begin{pmatrix}14&28\\28&56\end{pmatrix} has determinant 00.
  • Ridge regression (P3.A6). Adding a multiple of the identity fixes this: X⊤X+λI\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I} is invertible for every λ>0\lambda>0. In the example with λ=1\lambda=1 it is (15282857)\begin{pmatrix}15&28\\28&57\end{pmatrix}, with determinant 15⋅57−28⋅28=71≠015\cdot57-28\cdot28=71\ne0. It also improves the condition number, which tames the wild weights of the last section. (Why it always works is explained in P3.A6 and uses eigenvalues, P1.B12.)
  • Newton’s method (P1.F6). To minimize a function, Newton’s method steps by an amount d\mathbf{d} that solves Hd=−g\mathbf{H}\mathbf{d}=-\mathbf{g}, where g\mathbf{g} is the gradient and H\mathbf{H} is the Hessian matrix of second derivatives (P1.C8). It is a linear system, solved with solve and not by inverting H\mathbf{H}. For millions of parameters this solve is too expensive, which is one reason it is rarely used at scale.
  • Invertible layers and flows (P8.6). A normalizing flow is built from steps that can be run backwards, so that the model can map data to noise and noise to data. That needs each step to be invertible and, ideally, its inverse and determinant to be cheap (P1.B8). A general weight matrix is invertible if its determinant is not 00 (which is almost certainly the case for a random square matrix), but a ReLU layer is not invertible, because it sends every negative number to 00.
  • Orthogonal matrices (P1.B10). A rotation is undone by its transpose. Matrices with this property, called orthogonal, have the cheapest possible inverse: Q−1=Q⊤\mathbf{Q}^{-1}=\mathbf{Q}^\top.
  • Gaussians (P1.D7). The multivariate Gaussian density uses the inverse covariance matrix Σ−1\boldsymbol{\Sigma}^{-1} in its exponent; code computes Σ−1v\boldsymbol{\Sigma}^{-1}\mathbf{v} by solving Σu=v\boldsymbol{\Sigma}\mathbf{u}=\mathbf{v}.

Common mistakes

Check your understanding

  1. What is the inverse of (3124)\begin{pmatrix}3&1\\2&4\end{pmatrix}?

  2. Which of these matrices has no inverse?

  3. A\mathbf{A} and B\mathbf{B} are invertible n×nn\times n matrices. Which expression is always equal to (AB)−1(\mathbf{A}\mathbf{B})^{-1}?

  4. For A=(1224)\mathbf{A}=\begin{pmatrix}1&2\\2&4\end{pmatrix}, which right-hand side b\mathbf{b} gives a system Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} with infinitely many solutions?

  5. You need x\mathbf{x} with Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} for an invertible square A\mathbf{A}. Which call do numerical programmers prefer?

  6. A system Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} has a matrix with condition number 10610^6. What does that tell you?

  7. What is the inverse of the rotation of the plane by 40∘40^\circ?

Exercises

  1. Find the inverse of (4726)\begin{pmatrix}4&7\\2&6\end{pmatrix}, and check it by multiplying.
    Show answerdet⁡=4⋅6−7⋅2=10\det=4\cdot6-7\cdot2=10. Swap the diagonal and change the signs of the others: 110(6−7−24)=(0.6−0.7−0.20.4)\frac1{10}\begin{pmatrix}6&-7\\-2&4\end{pmatrix}=\begin{pmatrix}0.6&-0.7\\-0.2&0.4\end{pmatrix}. Check: the first row times the first column is 4⋅0.6+7⋅(−0.2)=2.4−1.4=14\cdot0.6+7\cdot(-0.2)=2.4-1.4=1, and the first row times the second column is 4⋅(−0.7)+7⋅0.4=−2.8+2.8=04\cdot(-0.7)+7\cdot0.4=-2.8+2.8=0, and so on, giving I\mathbf{I}.
  2. For which kk does (123k)\begin{pmatrix}1&2\\3&k\end{pmatrix} have no inverse?
    Show answerdet⁡=k−6\det=k-6, so there is no inverse for k=6k=6, when the second column (2,6)(2,6) is twice the first column (1,3)(1,3) (equivalently, row 2 is three times row 1). For every other kk the inverse exists.
  3. Find the inverse of the 90∘90^\circ rotation (0−110)\begin{pmatrix}0&-1\\1&0\end{pmatrix} and compare it with its transpose.
    Show answerdet⁡=0⋅0−(−1)⋅1=1\det=0\cdot0-(-1)\cdot1=1, so the inverse is 11(01−10)=(01−10)\frac11\begin{pmatrix}0&1\\-1&0\end{pmatrix}=\begin{pmatrix}0&1\\-1&0\end{pmatrix}, the rotation by −90∘-90^\circ. This is exactly the transpose of the original matrix.
  4. Solve x1+2x2=4x_1+2x_2=4 and 3x1+4x2=103x_1+4x_2=10 by elimination.
    Show answerR2−3R1R_2-3R_1 gives −2x2=−2-2x_2=-2, so x2=1x_2=1, and then x1+2=4x_1+2=4 gives x1=2x_1=2. The solution is (2,1)(2,1). Check: 3⋅2+4⋅1=103\cdot2+4\cdot1=10.
  5. Say whether each system has one solution, none or infinitely many, and why: (a) x1+x2=2x_1+x_2=2 and 2x1+2x2=42x_1+2x_2=4; (b) x1+x2=2x_1+x_2=2 and 2x1+2x2=52x_1+2x_2=5; (c) x1−x2=0x_1-x_2=0 and x1+x2=2x_1+x_2=2.
    Show answer(a) Infinitely many: the second equation is twice the first, so they are the same line. (b) None: the lines are parallel, since doubling the first equation gives 2x1+2x2=42x_1+2x_2=4, not 55 (elimination ends with 0=10=1). (c) One solution, (1,1)(1,1): the lines have different directions (det⁡=1⋅1−(−1)⋅1=2≠0\det=1\cdot1-(-1)\cdot1=2\ne0).
  6. Write (ABC)−1(\mathbf{A}\mathbf{B}\mathbf{C})^{-1} in terms of the inverses of the three matrices, and explain with shoes.
    Show answerC−1B−1A−1\mathbf{C}^{-1}\mathbf{B}^{-1}\mathbf{A}^{-1}. ABC\mathbf{A}\mathbf{B}\mathbf{C} applies C\mathbf{C} first, then B\mathbf{B}, then A\mathbf{A} (socks, shoes, then boots). To undo it, you undo the last step first: A−1\mathbf{A}^{-1}, then B−1\mathbf{B}^{-1}, then C−1\mathbf{C}^{-1}, and a product applies its rightmost factor first.
  7. A 2×22\times2 matrix A\mathbf{A} has det⁡A=4\det\mathbf{A}=4. What is det⁡((2A)−1)\det\bigl((2\mathbf{A})^{-1}\bigr)?
    Show answerdet⁡(2A)=22⋅4=16\det(2\mathbf{A})=2^2\cdot4=16 (P1.B8), and the determinant of the inverse is the reciprocal, so 1/161/16. Equivalently (2A)−1=12A−1(2\mathbf{A})^{-1}=\tfrac12\mathbf{A}^{-1} has det⁡=14⋅14\det=\tfrac14\cdot\tfrac14.
  8. Solve by elimination the system x+y+z=6x+y+z=6, 2x+3y+z=112x+3y+z=11, x+2y+4z=17x+2y+4z=17.
    Show answerR2−2R1R_2-2R_1 gives y−z=−1y-z=-1 and R3−R1R_3-R_1 gives y+3z=11y+3z=11. Then subtracting these two, 4z=124z=12, so z=3z=3; then y=2y=2 and x=6−2−3=1x=6-2-3=1. The solution is (1,2,3)(1,2,3), and the pivots are 1,1,41,1,4.
  9. Solve (1111.01)x=(22.01)\begin{pmatrix}1&1\\1&1.01\end{pmatrix}\mathbf{x}=\binom{2}{2.01} and then with the right-hand side (22.02)\binom{2}{2.02}. What does the change tell you?
    Show answerThe first system has the solution (1,1)(1,1). Subtracting the first equation from the second leaves 0.01 x2=0.010.01\,x_2=0.01 for the first system and 0.01 x2=0.020.01\,x_2=0.02 for the second, so the second solution is x2=2x_2=2 and x1=0x_1=0, that is (0,2)(0,2). A change of 0.010.01 in b2b_2 (about 0.35%0.35\% of the size of b\mathbf{b}) moved the solution from (1,1)(1,1) to (0,2)(0,2), a change of 100%100\% of its size: a magnification of about 280280. The condition number of the matrix is about 400400, which allows this.
  10. For X=(122436)\mathbf{X}=\begin{pmatrix}1&2\\2&4\\3&6\end{pmatrix}, compute X⊤X\mathbf{X}^\top\mathbf{X} and its determinant, then do the same for X⊤X+I\mathbf{X}^\top\mathbf{X}+\mathbf{I}.
    Show answerX⊤X=(14282856)\mathbf{X}^\top\mathbf{X}=\begin{pmatrix}14&28\\28&56\end{pmatrix} with det⁡=14⋅56−28⋅28=784−784=0\det=14\cdot56-28\cdot28=784-784=0, because column 2 of X\mathbf{X} is twice column 1. Adding I\mathbf{I} gives (15282857)\begin{pmatrix}15&28\\28&57\end{pmatrix} with det⁡=855−784=71≠0\det=855-784=71\ne0, so it is invertible. This is the idea of ridge regression.
  11. Code: without running it, predict what np.linalg.inv(np.array([[1, 2], [2, 4]])) does, then run it.
    Show answerThe matrix is singular (det⁡=0\det=0), so NumPy raises numpy.linalg.LinAlgError: Singular matrix. (The elimination meets an exact zero here. For a matrix that is singular on paper but has rounding in it, the behaviour can differ, as in P1.B8.)

Key takeaways

  • The inverse A−1\mathbf{A}^{-1} of a square matrix is the map that undoes A\mathbf{A}: A−1A=AA−1=I\mathbf{A}^{-1}\mathbf{A}=\mathbf{A}\mathbf{A}^{-1}=\mathbf{I}. For 2×22\times2 it is 1ad−bc(d−b−ca)\frac{1}{ad-bc}\begin{pmatrix}d&-b\\-c&a\end{pmatrix}. The columns of A−1\mathbf{A}^{-1} are the inputs that A\mathbf{A} sends to e1\mathbf{e}_1 and e2\mathbf{e}_2.
  • A matrix has no inverse when it squashes the plane: det⁡=0\det=0, dependent columns, rank below nn. Then different inputs share one output (the projection of P1.B5), so there is no way back. For a square matrix all of these mean the same thing, and only square matrices have a two-sided inverse.
  • Inverse rules: (AB)−1=B−1A−1(\mathbf{A}\mathbf{B})^{-1}=\mathbf{B}^{-1}\mathbf{A}^{-1} (undo the last step first, like socks and shoes), (A⊤)−1=(A−1)⊤(\mathbf{A}^\top)^{-1}=(\mathbf{A}^{-1})^\top, (cA)−1=1cA−1(c\mathbf{A})^{-1}=\frac1c\mathbf{A}^{-1}, (A−1)−1=A(\mathbf{A}^{-1})^{-1}=\mathbf{A}, det⁡A−1=1/det⁡A\det\mathbf{A}^{-1}=1/\det\mathbf{A}. But (A+B)−1(\mathbf{A}+\mathbf{B})^{-1} is not A−1+B−1\mathbf{A}^{-1}+\mathbf{B}^{-1}, and A−1\mathbf{A}^{-1} is not the entry-by-entry reciprocal.
  • A system Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} asks which combination of the columns of A\mathbf{A} gives b\mathbf{b}, or where the lines (one per equation) meet. There is exactly one solution when A\mathbf{A} is invertible, none when b\mathbf{b} is outside the column space, and infinitely many when b\mathbf{b} is inside it and the null space is bigger than 0\mathbf{0}.
  • Elimination solves a system: use row operations to reach a triangular form, then back substitution. A zero row reads 0=00=0 (infinitely many solutions) or 0=c0=c (none). The number of pivots is the rank.
  • In code, solve the system instead of forming the inverse: np.linalg.solve(A, b) takes fewer operations and is usually at least as accurate as np.linalg.inv(A) @ b. Check an inverse with np.allclose, not ==.
  • A nearly singular matrix has a huge condition number, and then tiny errors in b\mathbf{b} turn into huge errors in x\mathbf{x}. That is a property of the problem, not of the method.
Found a mistake? Tell us