Linear Algebra with NumPy: Dot Product, @, Determinant, Inverse and solve
Linear algebra in NumPy with simple maths: the dot product as a shopping bill, matrix multiplication with @, the determinant as a stretch, the inverse, and solving 2x + y = 5 and x + 3y = 7 in one line.
What you will learn
- Compute a dot product and explain it as pair up, multiply, add
- Multiply matrices with @ and read each cell as one row meeting one column
- Find a determinant and an inverse, and recognise a singular matrix
- Solve a system of equations with np.linalg.solve instead of the inverse
Before you start
- NumPy arrays and shapes
- NumPy reshape and transpose
Linear algebra sounds heavy, but in NumPy you need only a handful of ideas, and we'll keep the maths simple. You'll multiply arrays with the dot product and matrix multiply, find a determinant and an inverse, and solve equations in one line.
The dot product is a shopping bill
Say a holds how many of each item you buy, and b holds the prices.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.dot(a, b))
print(a @ b)
32
32
A dot product pairs them up and multiplies each pair: 4, 10 and 18. Then it adds those up, and the bill comes to 32. One single number.
The short form is a @ b. You've seen @ on top of a function as a decorator; that's a different job. Between two arrays, @ means matrix multiply.
One row meets one column
Matrix multiplication is built from that same idea.
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[7, 8], [9, 10], [11, 12]])
row = A[0]
col = B[:, 0]
print(row)
print(col)
print(row * col)
print((row * col).sum())
print((A @ B)[0, 0])
[1 2 3]
[ 7 9 11]
[ 7 18 33]
58
58
row * col multiplies pair by pair and keeps all three values. .sum() adds them to 58. That's one dot product, and it's exactly the top-left cell of A @ B.
The full multiplication
print(A.shape, B.shape)
print(A @ B)
print((A @ B).shape)
print(np.array_equal(A @ B, np.matmul(A, B)))
(2, 3) (3, 2)
[[ 58 64]
[139 154]]
(2, 2)
True
The inner numbers of the shapes, 3 and 3, have to match. That's the shape error from reshaping and transposing. The outer numbers, 2 and 2, give the result shape. np.matmul is the long name for @, and NumPy runs it in compiled code, so you never write these loops yourself.
The determinant
import numpy as np
M = np.array([[2, 1], [1, 3]])
d = np.linalg.det(M)
print(round(float(d), 2))
5.0
The determinant is one number you get from a square matrix. For a 2 by 2, multiply one diagonal (2 × 3 = 6), then the other (1 × 1 = 1), and subtract: 6 − 1 = 5. np.linalg.det returns a NumPy decimal that can carry tiny rounding errors, so the code turns it into a float and rounds it.
What does 5 mean? Picture a square of area one. This matrix stretches it into a slanted shape of area five. So the determinant tells you how much a matrix stretches things, and if it isn't zero, that stretch can be undone.
The inverse undoes a matrix
With plain numbers, 5 × 0.2 = 1, so 0.2 undoes 5. A matrix can have a partner like that too.
inv = np.linalg.inv(M)
print(np.round(inv, 2))
print(np.allclose(M @ inv, np.eye(2)))
[[ 0.6 -0.2]
[-0.2 0.4]]
True
M @ inv should give the matrix version of one: the identity matrix, with ones on the diagonal and zeros elsewhere, which np.eye(2) builds. allclose compares them while allowing for tiny rounding errors, and prints True.
When there's no inverse
import numpy as np
S = np.array([[1, 2], [2, 4]])
print(round(float(np.linalg.det(S)), 2))
print(np.linalg.inv(S))
0.0
Traceback (most recent call last):
File "S05L06_LinearAlgebra/singular_matrix.py", line 6, in <module>
print(np.linalg.inv(S))
~~~~~~~~~~~~~^^^
File "site-packages/numpy/linalg/_linalg.py", line 659, in inv
ainv = _umath_linalg.inv(a, signature=signature)
File "site-packages/numpy/linalg/_linalg.py", line 144, in _raise_linalgerror_singular
raise LinAlgError("Singular matrix")
numpy.linalg.LinAlgError: Singular matrix
The second row is just the first row times two. So the determinant is 1 × 4 − 2 × 2 = 0: the square gets squashed flat into a line, and there's no way back. Singular is the word for a matrix with no inverse. A determinant of zero means no inverse, and this error is how NumPy tells you.
Solving A x = b
Here's the useful part. Two equations, two unknowns:
import numpy as np
# 2x + y = 5
# x + 3y = 7
A = np.array([[2, 1], [1, 3]])
b = np.array([5, 7])
x = np.linalg.solve(A, b)
print("x =", x)
print("Check:", np.allclose(A @ x, b))
x = [1.6 1.8]
Check: True
The numbers in front of x and y go into A: 2 and 1 from the first equation, 1 and 3 from the second (no number written means 1). The right-hand sides, 5 and 7, go into b. That's why it's written A x = b. solve gives x = 1.6 and y = 1.8.
Check by hand: 2 × 1.6 + 1.8 = 5, and 1.6 + 3 × 1.8 = 7. The last line does the same check with allclose.
Prefer solve over the inverse
x1 = np.linalg.solve(A, b)
x2 = np.linalg.inv(A) @ b
print(np.round(x1, 2))
print(np.round(x2, 2))
print(np.allclose(x1, x2))
[1.6 1.8]
[1.6 1.8]
True
Both give the same answer. But the inverse route builds a whole extra matrix you don't need: more work, and more room for rounding errors. solve goes straight to the answer. If an AI tool hands you np.linalg.inv(A) @ b, add one line to your prompt: "use np.linalg.solve". Keep the inverse for when you need the inverse itself.
Recap
| Tool | What it gives you |
|---|---|
a @ b on vectors, np.dot | One number: pair up, multiply, add |
A @ B, np.matmul | A matrix; each cell is one row meeting one column; inner sizes must match |
np.linalg.det | How much the matrix stretches; zero means no inverse |
np.linalg.inv | The matrix that undoes it; LinAlgError: Singular matrix if none |
np.linalg.solve(A, b) | The unknowns in A x = b |
If you're heading into machine learning, you'll go deeper into this maths later. For everyday Python work, this is plenty. To see the same @ scoring a thousand embeddings at once, read NumPy and pandas for AI Engineers.
Try it yourself: change solve_system.py to solve 3x + y = 9 and x + 2y = 8. Or ask an AI tool to do it, then read every line it gives you.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
