NumPy 행렬 곱셈
NumPy 행렬 곱셈은 다음 세 가지 방법으로 수행할 수 있습니다.
- multiply(): 요소별 행렬 곱셈.
- matmul(): 두 배열의 행렬 곱.
- dot(): 두 배열의 내적.
1. NumPy 행렬 곱셈 요소 현명한
요소별 행렬 곱셈을 원하면 multiply() 함수를 사용할 수 있습니다.
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.multiply(arr1, arr2)
print(arr_result)
산출:
[[ 5 12]
[21 32]]
아래 이미지는 결과 행렬을 얻기 위해 수행되는 곱셈 연산을 보여줍니다.
2. 두 개의 NumPy 어레이의 행렬 곱
두 배열의 행렬 곱을 원하면 matmul() 함수를 사용하십시오.
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.matmul(arr1, arr2)
print(f'Matrix Product of arr1 and arr2 is:\n{arr_result}')
arr_result = np.matmul(arr2, arr1)
print(f'Matrix Product of arr2 and arr1 is:\n{arr_result}')
산출:
Matrix Product of arr1 and arr2 is:
[[19 22]
[43 50]]
Matrix Product of arr2 and arr1 is:
[[23 34]
[31 46]]
아래 다이어그램은 결과 배열의 모든 인덱스에 대한 행렬 제품 작업을 설명합니다. 단순화를 위해 각 인덱스에 대해 첫 번째 배열의 행과 두 번째 배열의 열을 가져옵니다. 그런 다음 해당 요소를 곱한 다음 추가하여 행렬 곱 값에 도달합니다.
두 배열의 행렬 곱은 인수 위치에 따라 다릅니다. 따라서 matmul(A, B)는 matmul(B, A)와 다를 수 있습니다.
3. 두 NumPy 어레이의 내적
numpy dot() 함수는 두 배열의 내적을 반환합니다. 결과는 1차원 및 2차원 배열에 대한 matmul() 함수와 동일합니다.
import numpy as np
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
arr_result = np.dot(arr1, arr2)
print(f'Dot Product of arr1 and arr2 is:\n{arr_result}')
arr_result = np.dot(arr2, arr1)
print(f'Dot Product of arr2 and arr1 is:\n{arr_result}')
arr_result = np.dot([1, 2], [5, 6])
print(f'Dot Product of two 1-D arrays is:\n{arr_result}')
산출:
Dot Product of arr1 and arr2 is:
[[19 22]
[43 50]]
Dot Product of arr2 and arr1 is:
[[23 34]
[31 46]]
Dot Product of two 1-D arrays is:
17
권장 수치:
- numpy.square()
- NumPy sqrt() – 행렬 요소의 제곱근
- Python NumPy 자습서
참조
- numpy matmul()
- numpy 곱하기()