Matrix multiplication
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Matrix multiplication is the workhorse of graphics and machine learning. Multiply a 2 × 3 matrix by a 3 × 2 matrix by hand and watch each entry of the answer appear as a dot product: a row of the first matrix paired with a column of the second, multiplied pair by pair and added up. Then see the shape rule, why the order matters, the triple loop in Python, what it costs, and NumPy's @ operator.
Check the shapes first
A has 2 rows and 3 columns: it is 2 × 3. B is 3 × 2. You can multiply A by B only when A's columns match B's rows: 3 = 3. The result C takes A's rows and B's columns: 2 × 2.
>>> A = [[1, 2, 3], [4, 5, 6]] >>> B = [[7, 8], [9, 10], [11, 12]] >>> len(A), len(A[0]), len(B), len(B[0]) (2, 3, 3, 2)
اقرأ الدرس خطوة بخطوة
Check the shapes first
A has 2 rows and 3 columns: it is 2 × 3. B is 3 × 2. You can multiply A by B only when A's columns match B's rows: 3 = 3. The result C takes A's rows and B's columns: 2 × 2.
>>> A = [[1, 2, 3], [4, 5, 6]] >>> B = [[7, 8], [9, 10], [11, 12]] >>> len(A), len(A[0]), len(B), len(B[0]) (2, 3, 3, 2)One entry: a dot product
Each entry of C is a dot product. For row 1, column 1, pair row 1 of A with column 1 of B, multiply each pair and add: 1×7 + 2×9 + 3×11 = 7 + 18 + 33 = 58.
>>> row, col = [1, 2, 3], [7, 9, 11] >>> [a * b for a, b in zip(row, col)] [7, 18, 33] >>> sum(a * b for a, b in zip(row, col)) 58Same row, next column
Keep row 1 of A and move to column 2 of B: 1×8 + 2×10 + 3×12 = 8 + 20 + 36 = 64. The answer lands where that row and that column cross: row 1, column 2 of C.
>>> sum(a * b for a, b in zip([1, 2, 3], [8, 10, 12])) 64Row 2 fills the rest
Row 2 of A works the same way. With column 1: 4×7 + 5×9 + 6×11 = 139. With column 2: 4×8 + 5×10 + 6×12 = 154. Four dot products, one per entry, fill C.
>>> r2 = [4, 5, 6] >>> sum(a * b for a, b in zip(r2, [7, 9, 11])), sum(a * b for a, b in zip(r2, [8, 10, 12])) (139, 154)The rule in symbols
In symbols, cᵢⱼ is the sum over k of aᵢₖ × bₖⱼ: row i of A slides along column j of B. If A is n × m and B is m × p, then C is n × p.
>>> A = [[1, 2, 3], [4, 5, 6]] >>> B = [[7, 8], [9, 10], [11, 12]] >>> [[sum(A[i][k] * B[k][j] for k in range(3)) for j in range(2)] for i in range(2)] [[58, 64], [139, 154]]Columns: matrix times vector
Read C by columns: column 1 of C is A times column 1 of B, a matrix times a vector. Graphics and machine learning do this constantly: a transform or a layer of weights times a column of numbers.
>>> import numpy as np >>> A = np.array([[1, 2, 3], [4, 5, 6]]) >>> A @ np.array([7, 9, 11]) array([ 58, 139]) >>> A @ np.array([8, 10, 12]) array([ 64, 154])Order matters
B times A is also allowed: B has 2 columns and A has 2 rows. But BA is 3 × 3, not 2 × 2. Even for square matrices, AB and BA are usually different, so never swap the order.
>>> import numpy as np >>> A = np.array([[1, 2, 3], [4, 5, 6]]) >>> B = np.array([[7, 8], [9, 10], [11, 12]]) >>> (B @ A).shape (3, 3) >>> B @ A array([[ 39, 54, 69], [ 49, 68, 87], [ 59, 82, 105]])Three loops in Python
In Python, three nested loops do it. i picks a row of A, j a column of B, and k walks along both, adding one product each time. Python counts from 0, so C[0][0] is c₁₁.
>>> A = [[1, 2, 3], [4, 5, 6]] >>> B = [[7, 8], [9, 10], [11, 12]] >>> C = [[0, 0], [0, 0]] >>> for i in range(2): ... for j in range(2): ... for k in range(3): ... C[i][j] += A[i][k]*B[k][j] ... >>> C [[58, 64], [139, 154]]Counting the work
The innermost line runs once for every i, j and k: 2 × 2 × 3 = 12 multiplications. Two n × n matrices take n³, so doubling n makes the work 8 times bigger.
>>> count = 0 >>> for i in range(2): ... for j in range(2): ... for k in range(3): ... count += 1 ... >>> count 12 >>> 100**3, 200**3 # double n: 8 times the work (1000000, 8000000)NumPy does it with @
Real code calls a library. NumPy's @ operator multiplies matrices: np.array(A) @ B gives [[58, 64], [139, 154]], the same C, and it runs the loops in fast compiled code.
>>> import numpy as np >>> A = [[1, 2, 3], [4, 5, 6]] >>> B = [[7, 8], [9, 10], [11, 12]] >>> np.array(A) @ B array([[ 58, 64], [139, 154]]) >>> (np.array(A) @ B).tolist() [[58, 64], [139, 154]]
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A is a 4 × 2 matrix and B is a 2 × 5 matrix. What is the shape of AB?
The inner sizes match (2 = 2), so AB exists. It takes A's rows and B's columns: 4 × 5.
02With A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]], what is the entry in row 2, column 1 of AB?
Row 2 of A is (3, 4) and column 1 of B is (5, 7): 3 × 5 + 4 × 7 = 15 + 28 = 43. The full product is [[19, 22], [43, 50]].
03A is 2 × 3 and B is 3 × 2. Which statement is true?
AB needs A's 3 columns to match B's 3 rows; BA needs B's 2 columns to match A's 2 rows. Both work, but the results have different shapes, so AB ≠ BA.
04Multiplying two n × n matrices with the three-loop method takes n³ multiplications. Roughly how much more work is it to go from n = 100 to n = 300?
Tripling n multiplies n³ by 3³ = 27: 300³ = 27,000,000 against 100³ = 1,000,000.
05In the loop C[i][j] += A[i][k] * B[k][j], what does k do?
i picks the row and j the column of the entry being built; k steps through the pairs a_ik and b_kj that are multiplied and added into that entry.
المسرد
- Matrix
- A rectangle of numbers in rows and columns. An n × m matrix has n rows and m columns.
- Entry
- One number in a matrix, named by its row and column: a₁₂ is in row 1, column 2 of A.
- Dot product
- Multiply two equal-length lists pair by pair and add the results: (1, 2, 3) · (7, 9, 11) = 7 + 18 + 33 = 58.
- Inner dimensions
- The column count of the first matrix and the row count of the second. They must be equal for the product to exist.
- Commutative
- An operation where the order does not matter, like 3 × 4 = 4 × 3. Matrix multiplication is not commutative.
- Identity matrix
- A square matrix with 1s on the diagonal and 0s elsewhere. Multiplying by it leaves a matrix unchanged.
- Vector
- A list of numbers, written as a matrix with one column. A matrix times a vector gives a new vector.
- @ operator
- Python's matrix multiplication operator (PEP 465, Python 3.5). NumPy arrays use it: A @ B.
الملاحظات والمصادر
- Maths numbers rows and columns from 1, so c₁₁ is row 1, column 1. Python lists count from 0, so the same entry is C[0][0].
- Matrix multiplication is associative, (AB)C = A(BC), and distributes over addition, A(B + C) = AB + AC, but it is not commutative: AB and BA usually differ.
- The identity matrix I has 1s on its diagonal and 0s elsewhere. AI = A and IA = A whenever the sizes fit, just like multiplying a number by 1.
- A vector is a matrix with one column. A 2 × 3 matrix times a 3-entry vector gives a 2-entry vector: A · (7, 9, 11) = (58, 139).
- The three-loop method needs n³ multiplications for two n × n matrices. Strassen (1969) showed about n^2.81 is enough (2.81 ≈ log₂ 7).
- MIT OCW 18.06 Linear Algebra (Strang), Lecture 3: Multiplication and inverse matrices
- G. Strang, Introduction to Linear Algebra, 5th ed., section 2.4 Rules for Matrix Operations
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 3rd ed., section 4.2 (matrix multiplication and Strassen)
- V. Strassen, Gaussian elimination is not optimal, Numerische Mathematik 13 (1969)
- PEP 465: A dedicated infix operator for matrix multiplication
- NumPy reference: numpy.matmul
اختبار يتاح بعد الخطوة الأخيرة.