TExcelTAD
Home › Math for Machine Learning › Data as Vectors and Matrices

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 DD numbers, its features, collected in a vector x∈RD\mathbf{x} \in \mathbb{R}^D. Categorical features are encoded as numbers first (one-hot encoding turns "red/green/blue" into (1,0,0)(1,0,0), (0,1,0)(0,1,0), (0,0,1)(0,0,1)). A dataset of NN examples stacks the vectors as rows of the data matrix

X=[x1Tx2T⋮xNT]∈RN×D,Xnd=feature d of example nX = \begin{bmatrix} \mathbf{x}_1^T \\ \mathbf{x}_2^T \\ \vdots \\ \mathbf{x}_N^T \end{bmatrix} \in \mathbb{R}^{N \times D}, \qquad X_{nd} = \text{feature } d \text{ of example } n

Targets (prices, labels) form a vector y∈RN\mathbf{y} \in \mathbb{R}^N.

Matrix operations you will use constantly

  • Product. For A∈Rm×nA \in \mathbb{R}^{m \times n} and B∈Rn×kB \in \mathbb{R}^{n \times k}, (AB)ij=∑l=1nailblj(AB)_{ij} = \sum_{l=1}^{n} a_{il} b_{lj}. Inner dimensions must match; the product is not commutative.
  • Transpose. (AT)ij=aji(A^T)_{ij} = a_{ji} and (AB)T=BTAT(AB)^T = B^T A^T.
  • Inverse. A square AA is invertible if some A−1A^{-1} gives AA−1=IAA^{-1} = I; then (AB)−1=B−1A−1(AB)^{-1} = B^{-1}A^{-1}.
  • Symmetric. A=ATA = A^T. The Gram matrix XTXX^T X is always symmetric.

A linear model predicts f(x)=θTxf(\mathbf{x}) = \boldsymbol{\theta}^T \mathbf{x}. For all examples at once:

y^=Xθ,y^n=∑d=1DXnd θd\hat{\mathbf{y}} = X\boldsymbol{\theta}, \qquad \hat{y}_n = \sum_{d=1}^{D} X_{nd}\,\theta_d
python · try it yourself
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 y^n\hat{y}_n is a dot product of a row of XX with θ\boldsymbol{\theta} (row view). The whole vector y^\hat{\mathbf{y}} is also a weighted sum of the columns of XX (column view):

Xθ=θ1c1+θ2c2+⋯+θDcDX\boldsymbol{\theta} = \theta_1 \mathbf{c}_1 + \theta_2 \mathbf{c}_2 + \cdots + \theta_D \mathbf{c}_D

where cd\mathbf{c}_d is column dd. The column view explains why predictions of a linear model can only live in the column space of XX, which becomes the geometry of least squares later in the course.

python · try it yourself
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 f(x)=θ0+θTxf(\mathbf{x}) = \theta_0 + \boldsymbol{\theta}^T\mathbf{x} has an intercept. Append a constant feature 1 to every example and the intercept becomes just another weight: X←[1 X]X \leftarrow [\mathbf{1}\ X]. This "bias trick" keeps every model in the clean form XθX\boldsymbol{\theta}.

In software

  • Tabular data in pandas becomes a NumPy matrix through df.to_numpy(); scikit-learn's fit(X, y) expects exactly this N×DN \times D layout (NumPy and pandas for ML).
  • fit_intercept=True in scikit-learn's linear models is the bias trick done for you.
  • Images are matrices (or 3-D arrays with colour channels); flattening a 28×2828 \times 28 image gives a vector in R784\mathbb{R}^{784}.

Exercises

Exercise 1: Can you multiply?

AA is 3×43 \times 4 and BB is 3×23 \times 2. Which of ABAB, ATBA^T B, BTAB^T A are defined, and what are their shapes?

Answer

ABAB is undefined; ATBA^T B is 4×24 \times 2; BTAB^T A is 2×42 \times 4.

Solution

ABAB needs the 4 columns of AA to match the 3 rows of BB: no. ATA^T is 4×34 \times 3, times 3×23 \times 2 gives 4×24 \times 2. BTB^T is 2×32 \times 3, times 3×43 \times 4 gives 2×42 \times 4. Note BTA=(ATB)TB^T A = (A^T B)^T.

Exercise 2: Predict by hand

With θ=(2,−1)\boldsymbol{\theta} = (2, -1), predict both examples of X=[1340]X = \begin{bmatrix} 1 & 3 \\ 4 & 0 \end{bmatrix}.

Answer

y^=(−1,8)\hat{\mathbf{y}} = (-1, 8).

Solution
y^1=1⋅2+3⋅(−1)=−1y^2=4⋅2+0⋅(−1)=8\begin{aligned} \hat{y}_1 &= 1 \cdot 2 + 3 \cdot (-1) = -1 \\ \hat{y}_2 &= 4 \cdot 2 + 0 \cdot (-1) = 8 \end{aligned}

Exercise 3: Transpose of a product (code)

Check numerically that (AB)T=BTAT(AB)^T = B^T A^T but in general (AB)T≠ATBT(AB)^T \ne A^T B^T, using two random 3×33 \times 3 matrices.

Answer

The first identity holds (True), the second does not (False).

Solution
python · try it yourself
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 (i,j)(i, j) of (AB)T(AB)^T is row jj of AA times column ii of BB, which is row ii of BTB^T times column jj of ATA^T: the order must flip.

Test yourself

If XX is N×DN \times D and θ∈RD\boldsymbol{\theta} \in \mathbb{R}^D, the vector XθX\boldsymbol{\theta} is…

  1. a weighted sum of the rows of XX
  2. a weighted sum of the columns of XX
  3. always the zero vector
  4. a D×DD \times D matrix

The Gram matrix XTXX^T X is always…

  1. diagonal
  2. symmetric
  3. invertible
  4. N×NN \times N

The bias trick adds an intercept by…

  1. dividing every feature by its mean
  2. appending a constant feature 1 to every example
  3. squaring the features
  4. removing the first column