Python 矩阵乘法代码
在纯 Python 中执行矩阵乘法,无需依赖。运行我们的嵌套循环与优化结构的比较。
概述
矩阵乘法是线性代数、计算机图形学和机器学习中的基本数学运算。它涉及获取两个矩阵并通过计算行和列的点积来生成第三个矩阵。
To multiply matrix A by matrix B, the number of columns in A must equal the number of rows in B. The resulting matrix has the dimensions of A's rows and B's columns.
在纯 Python 中,矩阵乘法是使用三个嵌套循环实现的。 While easy to write, this O(n³) operation is slow, which is why data scientists use specialized library engines likeNumPyin production.
程式碼和執行輸出
使用嵌套循環和列表理解的純 Python 矩陣乘法。
matrix_mult.py
在編輯器中嘗試def multiply_matrices(A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])
if cols_A != rows_B:
raise ValueError("Cannot multiply: column size of A must match row size of B.")
# Initialize result matrix with zeros
result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]
# Iterate through rows of A
for i in range(rows_A):
# Iterate through columns of B
for j in range(cols_B):
# Iterate through rows of B (or columns of A)
for k in range(cols_A):
result[i][j] += A[i][k] * B[k][j]
return result
# 2x3 Matrix A
matrix_A = [
[1, 2, 3],
[4, 5, 6]
]
# 3x2 Matrix B
matrix_B = [
[7, 8],
[9, 10],
[11, 12]
]
print("Matrix A (2x3):", matrix_A)
print("Matrix B (3x2):", matrix_B)
res = multiply_matrices(matrix_A, matrix_B)
print("Product (2x2):", res)端子輸出
Matrix A (2x3): [[1, 2, 3], [4, 5, 6]]
Matrix B (3x2): [[7, 8], [9, 10], [11, 12]]
Product (2x2): [[58, 64], [139, 154]]逐步實施
- 数学图形渲染和坐标旋转
- 简单的人工神经网络层点积
- 了解算法结构和嵌套循环
常見問題解答
為什麼NumPy執行矩陣乘法的速度如此快速?
NumPy用 C 编写,并利用高度优化的 BLAS/LAPACK 库。它利用了向量化、CPU 快取優化和並行執行,這是標準 Python 循環無法做到的。
Python 中的“@”运算符是什么?
從Python 3.5 開始,引入了「@」符號作為矩陣乘法的專用中綴運算符,讓您在使用 numpy 陣列時執行「A @ B」。