Matrices
- Machine Learning course
- Beginner
- Lesson 32/112
- 5 min
A matrix is a 2-D array of numbers with rows and columns.
Matrices
A matrix is a two-dimensional table of numbers. In ML a dataset is a matrix: each row of X is an example and each column a feature. The weights of a neural network layer are a matrix too.
A = np.array([[1, 2],
[3, 4],
[5, 6]])
print(A.shape) # (3, 2): a 3x2 matrix
print(A[1]) # [3 4] second rowLike vectors, matrices are added element-wise and multiplied by scalars; the shapes must match.
Broadcasting
NumPy automatically expands arrays of different shapes if they follow the rules. The most common use is subtracting a vector from every row of a matrix:
X = np.array([[1, 10],
[3, 20],
[5, 30]])
ort = X.mean(axis=0) # [ 3. 20.] shape (2,)
print(X - ort) # subtract the mean from every row
# [[-2. -10.] [ 0. 0.] [ 2. 10.]]The rule: starting from the right, each dimension must be equal or 1.
Practice Centre
Subtract the column means of X from every row using broadcasting and print the result.
Starter code
import numpy as np
X = np.array([[2, 8], [4, 6], [6, 4]])
# buraya yazSample solution
import numpy as np
X = np.array([[2, 8], [4, 6], [6, 4]])
print(X - X.mean(axis=0))Expected output
[[-2. 2.] [ 0. 0.] [ 2. -2.]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can two matrices of shapes (3, 2) and (2, 3) be added with <code>+</code>?
- Yes, it becomes (3, 3)
- Yes, it becomes (2, 2)
- Yes, always
- No; the shapes don't match Correct answer
Explanation: In element-wise operations the shapes must be the same or broadcastable; (3, 2) and (2, 3) aren't.
2 Subtract the column means from every row.
Xc = X - X.____(axis=0)
Xc = X - X.mean(axis=0)
Explanation: Broadcasting applies the (2,)-shaped mean to every row.
3 Match the shape pairs with the results.
| Term | Meaning |
|---|---|
(3, 2) + (2,) |
(3, 2) |
(3, 2) + (3, 1) |
(3, 2) broadcast |
(3, 2) + (3,) |
Error |
(3, 2) * 2 |
Scalar multiplication |