holehouse.org Blog Machine learning notes

03: Linear Algebra - Review

Matrices - overview

A=[1402191137182194914371471448] A11=1402A12=191 A32=1437A41=147 Aij is the entry in the ith row and jth column.
A[0, 0]          # 1402   the notes' A11
A[0, 1]          # 191    the notes' A12
A[2, 1]          # 1437   the notes' A32
A[3, 0]          # 147    the notes' A41
NumPy indexes from 0, so the notes' A32 is A[2, 1] — subtract one from each index.

Vectors - overview

y=[460232315178]
y = np.array([460, 232, 315, 178])
y.shape          # (4,)    a 1-D array, not a column

y_col = y.reshape(4, 1)
y_col.shape      # (4, 1)  an explicit column vector
A 1-D array has no orientation — it is neither a row nor a column. Reshape when the distinction matters.

Matrix manipulation

[102531]+[40.52501]=[50.541032]
M = np.array([[1, 0], [2, 5], [3, 1]])
N = np.array([[4, 0.5], [2, 5], [0, 1]])

M + N            # [[5, 0.5], [4, 10], [3, 2]]
3×[102531]=[3061593]
3 * M            # [[3, 0], [6, 15], [9, 3]]
3×[142]+[005]−[302]/3
a = np.array([1, 4, 2])
b = np.array([0, 0, 5])
c = np.array([3, 0, 2])

3 * a + b - c / 3    # [2.,  12.,  10.33333333]
Multiplication and division bind tighter than addition, so this evaluates in the order the maths above shows.
[134021]×[15]=[1647] 1×1+3×5=16 4×1+0×5=4 2×1+1×5=7 A [3 x 2] matrix times a [2 x 1] vector gives a [3 x 1] vector.
P = np.array([[1, 3], [4, 0], [2, 1]])   # [3 x 2]
v = np.array([[1], [5]])                 # [2 x 1]

P @ v            # [[16], [4], [7]]
@ is matrix multiplication. * multiplies element by element and is not the same thing.
[132401][130152]
A2 = np.array([[1, 3, 2], [4, 0, 1]])    # [2 x 3]
B2 = np.array([[1, 3], [0, 1], [5, 2]])  # [3 x 2]

A2 @ B2          # [[11, 10], [9, 14]]   a [2 x 2]
[132401]×[105]=[119] [132401]×[312]=[1014] Each column of the result comes from multiplying A by the corresponding column of B.
A2 @ B2[:, [0]]  # [[11], [9]]   first column of B
A2 @ B2[:, [1]]  # [[10], [14]]  second column of B
Each column of the product is A times the corresponding column of B, exactly as above.

Implementation/use

1.hθ(x)=−40+0.25x 2.hθ(x)=200+0.1x 3.hθ(x)=−150+0.4x [1210411416115341852]×[−40200−1500.250.10.4]=[486410692314342416344353464173285191] One column of predictions per hypothesis — twelve predictions from a single matrix multiplication. Values are rounded to whole numbers, as on the original slide.
thetas = np.array([[-40, 200, -150],
                   [0.25, 0.1,  0.4]])   # one column per hypothesis

np.round(X @ thetas)
# [[486., 410., 692.],
#  [314., 342., 416.],
#  [344., 353., 464.],
#  [173., 285., 191.]]
Twelve predictions from one call — this is why the vectorized form matters.

Matrix multiplication properties

Inverse and transpose operations

A=[120359]AT=[132509] The first row of A becomes the first column of AT, and so on.
D = np.array([[1, 2, 0], [3, 5, 9]])

D.T              # [[1, 3], [2, 5], [0, 9]]
D.shape, D.T.shape   # ((2, 3), (3, 2))