Data as Vectors and Matrices
Before any learning happens, data has to become numbers arranged in vectors and matrices. A house becomes a vector of features, a dataset becomes a matrix, and a linear model becomes a matrix-vector product. This lesson sets up that vocabulary and the matrix operations ML uses most.
Examples are vectors
An example (a house, an image, a customer) is described by numbers, its features, collected in a vector . Categorical features are encoded as numbers first (one-hot encoding turns "red/green/blue" into , , ). A dataset of examples stacks the vectors as rows of the data matrix
Targets (prices, labels) form a vector .
Matrix operations you will use constantly
- Product. For and , . Inner dimensions must match; the product is not commutative.
- Transpose. and .
- Inverse. A square is invertible if some gives ; then .
- Symmetric. . The Gram matrix is always symmetric.
A linear model predicts . For all examples at once:
import numpy as np
# 4 houses: size (100 m^2), rooms, age (decades)
X = np.array([[1.2, 3, 1.5],
[0.8, 2, 4.0],
[2.0, 5, 0.5],
[1.5, 4, 2.0]])
theta = np.array([150.0, 10.0, -8.0]) # price per unit of each feature (thousands)
y_hat = X @ theta
print("X shape:", X.shape, " predictions:", y_hat)
G = X.T @ X
print("Gram matrix symmetric:", np.allclose(G, G.T), " shape:", G.shape)X shape: (4, 3) predictions: [198. 108. 346. 249.]
Gram matrix symmetric: True shape: (3, 3)
Two ways to read a matrix product
Each prediction is a dot product of a row of with (row view). The whole vector is also a weighted sum of the columns of (column view):
where is column . The column view explains why predictions of a linear model can only live in the column space of , which becomes the geometry of least squares later in the course.
import numpy as np
X = np.array([[1.2, 3, 1.5], [0.8, 2, 4.0], [2.0, 5, 0.5], [1.5, 4, 2.0]])
theta = np.array([150.0, 10.0, -8.0])
row_view = np.array([X[n] @ theta for n in range(4)])
col_view = sum(theta[d] * X[:, d] for d in range(3))
print(row_view, col_view, np.allclose(row_view, col_view))[198. 108. 346. 249.] [198. 108. 346. 249.] True
Adding a bias with a column of ones
The model has an intercept. Append a constant feature 1 to every example and the intercept becomes just another weight: . This "bias trick" keeps every model in the clean form .
In software
- Tabular data in pandas becomes a NumPy matrix through
df.to_numpy(); scikit-learn'sfit(X, y)expects exactly this layout (NumPy and pandas for ML). fit_intercept=Truein scikit-learn's linear models is the bias trick done for you.- Images are matrices (or 3-D arrays with colour channels); flattening a image gives a vector in .
Exercises
Exercise 1: Can you multiply?
is and is . Which of , , are defined, and what are their shapes?
Answer
is undefined; is ; is .
Solution
needs the 4 columns of to match the 3 rows of : no. is , times gives . is , times gives . Note .
Exercise 2: Predict by hand
With , predict both examples of .
Answer
.
Solution
Exercise 3: Transpose of a product (code)
Check numerically that but in general , using two random matrices.
Answer
The first identity holds (True), the second does not (False).
Solution
import numpy as np
rng = np.random.default_rng(3)
A, B = rng.normal(size=(3, 3)), rng.normal(size=(3, 3))
print(np.allclose((A @ B).T, B.T @ A.T), np.allclose((A @ B).T, A.T @ B.T))True False
Entry of is row of times column of , which is row of times column of : the order must flip.
Test yourself
If is and , the vector is…
- a weighted sum of the rows of
- a weighted sum of the columns of
- always the zero vector
- a matrix
The Gram matrix is always…
- diagonal
- symmetric
- invertible
The bias trick adds an intercept by…
- dividing every feature by its mean
- appending a constant feature 1 to every example
- squaring the features
- removing the first column