-
Matrix Multiplication Code | Advanced Learning AlgorithmMachine Learning/Stanford ML Specialization 2024. 2. 10. 20:59
이제 전에 직접 계산했던것을 NumPy를 이용해서 계산해보자. 먼저 A matrix를 아래와 같이 생성할 수 있다.
A = np.array([1, -1, 0.1], [2, -2, 0.2]])
이제 이 matrix를 transpose 한 matrix를 생성해보자.
AT = np.array([[1, 2], [-1, -2], [0.1, 0.2]])
매번 이렇게 직접 쓰지 않아도, 원래의 matrix가 있다면, transpose를 이렇게 할 수 있다.
AT = A.T
그리고 W matrix를 정의해보자
W = np.array([[3, 5, 7, 9], [4, 6, 8, 0]])
이제 Z를 계산하려면, matmul 함수로 간단하게 계산할 수 있다.
Z = np.matmul(AT, W)
그러면 다음과 같은 matrix를 결과로 얻는다
[[11, 17, 23, 9],
[-11, -17, -23, -9],
[1.1, 1.7, 2.3, 0.9]
]이제, 이것을 이용해서 Dense layer의 vectorize를 살펴보자.
3개의 뉴런에는 각각의 weight vector들이 있고, b값이 해당된다. 이제 전에 배운 matrix multiplication을 이용해서 이것들이 어떻게 연산되는지 알아보자. 아래와 같이 A transpose, W, B matrix/vector들을 이용해서 Z 값을 계산하고, Z값을 g함수, 즉 sigmoid 함수에 넣어서 최종 A값을 계산해냈다. 각 뉴런에서 [1 0 1]의 값이 나왔다.
이것을 NumPy를 이용해서 계산해보자.
# AT, W, b를 생성했다. AT = np.array([[200, 17]]) W = np.array([[-1, -3, 5], [-2, 4, -6]]) b = np.array([[-1, 1, 2]]) # 그리고 이것들을 input으로 쓰는 dense 함수를 만든다 def dense(AT, W, b): z = np.matmul(AT, W) + b a_out = g(z) return a_out # [[1, 0, 1]]
현대 컴퓨터는 matmul과 같은 함수를 쓰는데 아주 능숙하다. 그래서 이렇게 vectorization을 해서 계산하게 되면, 훨씬 효율적이다.
Reference
Advanced Learning Algorithms
In the second course of the Machine Learning Specialization, you will: • Build and train a neural network with TensorFlow to perform multi-class ... 무료로 등록하십시오.
www.coursera.org
'Machine Learning > Stanford ML Specialization' 카테고리의 다른 글
TensorFlow Training Details | Advanced Learning Algorithm (0) 2024.02.11 TensorFlow Implementation | Advanced Learning Algorithm (0) 2024.02.11 Matrix Multiplication Rules | Advanced Learning Algorithm (0) 2024.02.10 Matrix Multiplication | Advanced Learning Algorithm (0) 2024.02.10 How Neural Networks are Implemented Efficiently(Feat. mutmul) | Advanced Learning Algorithm (1) 2024.02.10