Matrices and @
Not met yet
A matrix is a two-dimensional array: a table with one row per evening and one column per reading, or a grid of weights. A @ B multiplies matrices: each row of A meets each column of B, so entry [i, j] is the dot product of row i with column j. That makes (n, k) @ (k, m) give (n, m): the inner sizes must match and are used up, and X @ w gives one weighted sum per row of X. A.T, the transpose, swaps rows with columns, and A @ B is usually not the same as B @ A. A 2 by 2 matrix also moves arrows: with turn = [[0, -1], [1, 0]], turn @ arrow turns any arrow a quarter turn anticlockwise.
Try it
main.pyimport numpy as np
evenings = np.array([[1.0, 2.0, 0.0],
[3.0, 0.0, 1.0]]) # 2 evenings, 3 readings
weights = np.array([0.5, 1.0, -2.0])
print(evenings @ weights)
print(evenings.T.shape)
turn = np.array([[0, -1],
[1, 0]])
print(turn @ np.array([1, 0]))
Output
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks A @ B is the same as B @ A, as it would be for two ordinary numbers.
- Thinks the shape of (n, k) @ (k, m) keeps the shared size k, rather than the outer sizes (n, m).
- Thinks .T turns a one-dimensional array into a column or a row, when it hands it back unchanged.