Vectorization
벡터화를 통해 for-loops을 줄여 컴퓨터가 계산을 효율적으로 할 수 있게 할 수 있다.
More vectorization examples
Whenever possible, avoid explicit for-loops.
$$u = Av
\
u_i=\sum_i\sum_j A_{ij}v_j$$
- non-vectorized
u = np.zeros((n,1))
for i ...
for j ...
u[i] += A[i][j] * v[j]
- vectorized
u = np.dot(A,v)
Vectors and matrix valued functions
ex. 모든 matrix elements에 exponential operation을 해야할 때
- non-vectorized
u = np.zeros((n,1))
for i in range(n):
u[i] = math.exp(v[i])
- vectorized
import numpy as np
u = np.exp(v)
np.log(v)
np.abs(v)
np.maximum(v,0)
v**2
Logistic regression derivatives
- $dw$를 $n_x$에 대해 각각 지정하는 대신, 벡터화로 하나의 변수로 나타낼 수 있다.$dw +=x^{(i)}dz^{(i)}$
- $dw := dw / m$
- $dw=np.zeros((n-x,1))$
Vectorizing Logistic Regression
$z^{(i)}=w^Tx^{(i)}+b$
$a^{(i)}=\sigma(z^{(i)})$
$$X=[X^{(1)} \ X^{(2)} \ ... \ X^{(m)}]
\Z=[z^{(1)} \ z^{(2)} \ ... \ z^{(m)}]=w^TX+[b \ b\ b... \ b]
\
A=[a^{(1)},a^{(2)},...,a^{(m)}]=\sigma(z)
$$
- matrix Z는 파이썬에서 .dot (행렬 곱)을 통해 구할 수 있다.
z = np.dot(wT,X) + b
Vectorizing Logistic Regression's Gradient Computation
Vectorizing Logistic Regression
$$dz=[dz^{(1)} \ dz^{(2)} \ ... \ dz^{(m)}]
=A-Y
\=[a^{(1)}-y^{(1)} \ a^{(2)}-y^{(2)} \ ... \ a^{(m)}-y^{(m)}]$$
$$db = \frac 1 m \ np.sum(dz)
\
dw = \frac 1 m Xdz$$
$dz, dw, db$ 를 for-loop 없이 벡터화로 계산할 수 있다.
Broadcasting in Python
- python에서 $(m,n)$ matrix에 $(1,n) \ or \ (m,1)$ matrix를 연산하면 값이 자동으로 복사되어 같은 차원으로 만들어 연산된다.
a = np.random.randn(5,1) # a.shape = (5,1) -> column vector
a = np.random.randn(1,5) # a.shape = (1,5) -> row vector
Source
Neural Networks and Deep Learning
신경망 및 딥 러닝
deeplearning.ai에서 제공합니다. In the first course of the Deep Learning Specialization, you will study the foundational concept of neural networks and ... 무료로 등록하십시오.
www.coursera.org