NumPy · lesson 11 of 13
Parts in this lesson
Akilos @ pricemultiply in pairs, then add
BA @ Bevery row against every column
Cnp.linalg.solve(A, b)find x where A @ x is b
Da[:, np.newaxis] - a[np.newaxis, :]2.9: every row against every row

Linear algebra for data

Last updated

A lot of data work is multiplying things and adding them up: kilos times prices, totalled; weights times scores, totalled. Linear algebra is the maths of doing that for whole tables at once. In this lesson you'll use the dot product and matrix product, solve a pair of equations, and measure how alike two stores are.

By the end of this lesson you can

  • Work out a weighted total with the dot product, @
  • Multiply two tables with @, and predict the result’s shape
  • Solve a set of equations, such as finding prices from takings, with np.linalg.solve
  • Measure the distance between every pair of rows with broadcasting

The dot product

Batangas sold 40 kg of rice, 12 kg of sugar and 5 kg of oil, at ₱45, ₱60 and ₱90 a kilo. Its takings are each kilo figure times its price, added up. Run the cells.

dot.ipynb

That "multiply in pairs, then add" is the dot product. For two arrays a and b of the same length n,

a⋅b=∑i=1naibi=40×45+12×60+5×90=2970

In Python you write it @ (or np.dot, which you'll see in older code). The last cell is the difference from *: kilos * price stops after the multiplying, and gives three numbers. @ adds them up too, and gives one.

Weighted totals are everywhere in data: a basket's cost, a grade from weighted marks, a score from a model. They're all dot products.

Multiplying tables

Now two stores, and two things to work out for each: revenue and cost. That's a dot product for every store and every column. Step through.

A row meets a column, for every cell. Kilos sold by two stores (rows) of three items (columns), and each item’s price and cost per kilo. We want each store’s revenue and cost.4012535108453860529070kilos (2, 3)ricesugaroilBatangasLipaper kilo (3, 2)pricecostricesugaroilkilos @ per_kilo (2, 2)revenuecostBatangasLipa
1 of 5 Kilos sold by two stores (rows) of three items (columns), and each item’s price and cost per kilo. We want each store’s revenue and cost.
matmul.ipynb

Each cell of the answer is one dot product: row i of the first table with column j of the second,

(AB)ij=∑kAikBkj

The shapes follow one rule: the inner lengths must match, and they disappear.

(n×d)(d×k)→(n×k)(2×3)(3×2)→(2×2)

The last cell breaks it: (2, 3) @ (2, 3), and 3 doesn't match 2. When the shapes are the wrong way round, .T (lesson 2.4) usually fixes it: kilos.T is (3, 2).

Wrong way: * where @ was meant

Here the tables are 2 × 2: two stores, and just rice and sugar. Run it.

square.ipynb

Both lines run, and both give a 2 × 2 table. But only the second is revenue and cost. * multiplies element by element (lesson 2.7): Batangas's 40 kg of rice times ₱45, and its 12 kg of sugar times sugar's cost, ₱38, which is meaningless. Nothing is added up.

With the 2 × 3 tables in step 2, * would have failed, because the shapes don't match. With square tables, any two can be multiplied element by element, so the mistake is silent. Python added @ in 2014 partly to make this mix-up harder: * is always element by element, and @ is always the matrix product. Check you used the one you meant, and check one cell of the answer by hand.

Solving equations

Now the other way round. You know what two stores sold and what they took, but not the prices:

40price+12psugar=252035price+10psugar=2175

Put the kilos in a table A, the unknown prices in x and the takings in b, and the two equations are one: Ax=b. np.linalg.solve finds x. Run it.

prices.ipynb

₱45 for rice and ₱60 for sugar. The second cell checks the answer by putting it back: Ax gives the takings you started with. Always check like this. With real data, equations often have no exact answer, and Stage 9 shows how to find the closest one.

How alike are two stores?

Three stores' average day: kilos of rice, sugar and oil. Which stores are most alike? Treat each store as a point, and measure the straight-line distance between them. For two rows x and y,

‖x−y‖=∑j(xj−yj)2

This is Pythagoras, in as many directions as there are columns. Run the cells.

alike.ipynb

The first cell is broadcasting from lesson 2.9: a (3, 1, 3) minus a (1, 3, 3) gives every store minus every other store, (3, 3, 3). The second squares, adds across the items (axis=2) and takes the square root.

The answer is a table of distances. The diagonal is 0: every store is its own twin. Batangas and Tanauan are 1.7 apart, almost the same mix; Lipa is about 12 from both. Grouping stores, customers or products by distances like these is how clustering works, in Simple Machine Learning.

Check what you learned

np.array([1, 2, 3]) @ np.array([4, 5, 6]) is…
A is (10, 4) and B is (4, 3). What shape is A @ B?
You multiply two 3 × 3 tables with * and get a 3 × 3 answer with no error. What should you check?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis