NumPy Master Class
Chapter2 Arithmetic Operations: Notebook7 Matrix Multiplications
Shin's Lab
2020. 1. 8. 20:40
이번 notebook에서는 vector들의 dot product에 이어 matrix multiplication에 대해 알아보자.
이 matrix multiplication은 특히 data science에서 많은 data를 한 번에 처리할 때 항상 사용되는 연산이다.
그리고 조심할 점은 (m,n)*(n,p)처럼 가운데 2개의 차원이 동일해야 된다는 점이다.
matrix multiplication은 dot product와 마찬가지로 ndarray.dot()을 통해서 연산할 수 있다.
In [2]:
import numpy as np
Matrix Multiplications¶
In [5]:
operand1 = np.random.randint(low=0, high=5, size=(2,3))
operand2 = np.random.randint(low=0, high=5, size=(3,4))
print(operand1.shape, operand2.shape)
print("operand1:\n", operand1)
print("operand2:\n", operand2)
위와 같이 matrix 2개가 있을 때, 다음과 같이 matrix multiplication을 할 수 있다.
In [8]:
print("operand1.dot(operand2):\n", operand1.dot(operand2))
print("operand1.dot(operand2).shape:", operand1.dot(operand2).shape)
우리가 알던대로 (2,3)*(3,4)의 결과로 (2,4) dimension의 ndarray가 나오는 것을 알 수 있다.
그러면 연속해서 matrix multiplication이 진행될 땐 어떻게 해야할까?
In [11]:
operand1 = np.random.randint(low=0, high=5, size=(2,3))
operand2 = np.random.randint(low=0, high=5, size=(3,4))
operand3 = np.random.randint(low=0, high=5, size=(4,2))
result = operand1.dot(operand2)
print(result.shape)
위 결과를 다시 한 번 보면 operand1.dot(operand2)의 결과 자체도 matrix가 된다. 따라서 이 뒤에 다시 한 번 .dot() method를 사용할 수 있게 된다.
matrix multiplication의 내용은 간단하지만 앞으로 자주 나오므로 충분히 연습하고 다음 notebook으로 넘어가면 좋을 것 같다.