[PYTHON/NUMPY] 스트라센의 행렬 곱셈(Strassen’s Matrix Multiplication) 알고리즘을 사용해 행렬 곱하기
■ 스트라센의 행렬 곱셈(Strassen's Matrix Multiplication) 알고리즘을 사용해 행렬을 곱하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
import numpy as np def multiplyMatrixWithStrassenAlgorithm(matrix1, matrix2): matrix1Length = len(matrix1) if matrix1Length == 1: return matrix1 * matrix2 newSize = matrix1Length // 2 a11 = matrix1[:newSize, :newSize] a12 = matrix1[:newSize, newSize:] a21 = matrix1[newSize:, :newSize] a22 = matrix1[newSize:, newSize:] b11 = matrix2[:newSize, :newSize] b12 = matrix2[:newSize, newSize:] b21 = matrix2[newSize:, :newSize] b22 = matrix2[newSize:, newSize:] m1 = multiplyMatrixWithStrassenAlgorithm(a11 + a22, b11 + b22) m2 = multiplyMatrixWithStrassenAlgorithm(a21 + a22, b11) m3 = multiplyMatrixWithStrassenAlgorithm(a11, b12 - b22) m4 = multiplyMatrixWithStrassenAlgorithm(a22, b21 - b11) m5 = multiplyMatrixWithStrassenAlgorithm(a11 + a12, b22) m6 = multiplyMatrixWithStrassenAlgorithm(a21 - a11, b11 + b12) m7 = multiplyMatrixWithStrassenAlgorithm(a12 - a22, b21 + b22) c11 = m1 + m4 - m5 + m7 c12 = m3 + m5 c21 = m2 + m4 c22 = m1 - m2 + m3 + m6 return np.vstack((np.hstack((c11, c12)), np.hstack((c21, c22)))) sourcMatrix1 = np.array( [ [1 , 2 , 3 , 4 ], [5 , 6 , 7 , 8 ], [9 , 10, 11, 12], [13, 14, 15, 16] ] ) sourceMatrix2 = np.array( [ [17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [29, 30, 31, 32] ] ) targetMatrix = multiplyMatrixWithStrassenAlgorithm(sourcMatrix1, sourceMatrix2) print(targetMatrix) """ [[ 250 260 270 280] [ 618 644 670 696] [ 986 1028 1070 1112] [1354 1412 1470 1528]] """ |
▶ requirements.txt
1 2 3 |
numpy==2.0.0 |
※ pip install numpy