본문 바로가기

Andrew Ng(Deep Learning)

앤드류 응 교수님 딥러닝 학습일지 실습(1)

반응형

 

일본 여행을 갔다온다고 업로드가 늦었습니다.다시 달려보겠습니다. 오늘은 처음으로 실습을 가지고 돌아왔습니다. 

딥러닝 실습이라기보다는 그동안 배운 기초 개념을 파이썬으로 구현이라고 생각하면 되겠습니다.

 

처음으로 구현 해볼 것은 시그모이드 함수입니다.

import numpy as np

def sigmoid(x):
    s=1/(1+np.exp(-x))
    return s
 

다음은 시그모이드 함수의 도함수 구현입니다. 식 계산의 결과 시그모이드 함수의 도함수 f'=f(1-f)임을 알 수가 있었습니다.

def sigmoid_derivative(x):
    s=sigmoid(x)
    ds=s*(1-s)
    return ds
 

다음은 벡터를 reshape하는 과정입니다. 

이미지 인식을 훈련 시키려면 이미지를 하나의 벡터로 만들어줘야 하는데, RGB값과 같이 nxmx3 형태로 데이터가 주어지면 식을 변형하여,

1x(nxmx3)의 column vector로 만들어줘야 합니다.

def image2vector(image):
    v=image.reshape(image.shape[0]*image.shape[1]*image.shape[2],1)
    return v
 

다음은 하나의 행을 Normalize 하는 과정을 구현해보겠습니다.

    x_norm=np.linalg.norm(x,axis=1,keepdims=True)
    x=x/x_norm
    return x
 

numpy를 쓰면 선형대수학 함수를 그냥 불러오면 된다는 점이 놀라웠습니다. 역시 파이썬.

axis는 행을 기준으로 계산을 하겠다는 것이고, keepdims는 차원을 유지하여 broadcasting을 할 수 있게끔 하는 것입니다.

자세한 설명은  https://yeko90.tistory.com/entry/넘파이-기초-axis-keepdims-마스터하기 참고하시면 될 것 같습니다.

 

다음으로는 softmax function 구현입니다.

def softmax(x):
    exp_x=np.exp(x)
    softmax=exp_x/np.sum(exp_x,axis=1,keepdims=True)
    return softmax
 

다음은 Vectorization을 활용 할 수 있는 numpy 함수 설명 구현입니다.

Vectorization을 할 경우와 하지 않을 때를 통해 시간 차이를 알 수 있습니다.

import time

x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]

### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###
tic = time.process_time()
dot = 0
for i in range(len(x1)):
    dot+= x1[i]*x2[i]
toc = time.process_time()
print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### CLASSIC OUTER PRODUCT IMPLEMENTATION ###
tic = time.process_time()
outer = np.zeros((len(x1),len(x2))) # we create a len(x1)*len(x2) matrix with only zeros
for i in range(len(x1)):
    for j in range(len(x2)):
        outer[i,j] = x1[i]*x2[j]
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### CLASSIC ELEMENTWISE IMPLEMENTATION ###
tic = time.process_time()
mul = np.zeros(len(x1))
for i in range(len(x1)):
    mul[i] = x1[i]*x2[i]
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###
W = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array
tic = time.process_time()
gdot = np.zeros(W.shape[0])
for i in range(W.shape[0]):
    for j in range(len(x1)):
        gdot[i] += W[i,j]*x1[j]
toc = time.process_time()
print ("gdot = " + str(gdot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
 

 

x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]

### VECTORIZED DOT PRODUCT OF VECTORS ###
tic = time.process_time()
dot = np.dot(x1,x2)
toc = time.process_time()
print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### VECTORIZED OUTER PRODUCT ###
tic = time.process_time()
outer = np.outer(x1,x2)
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### VECTORIZED ELEMENTWISE MULTIPLICATION ###
tic = time.process_time()
mul = np.multiply(x1,x2)
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### VECTORIZED GENERAL DOT PRODUCT ###
tic = time.process_time()
dot = np.dot(W,x1)
toc = time.process_time()
print ("gdot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
 

Vectorization을 이용한 것이 훨씬 깔끔하고 빠른 것을 알 수 있습니다.

다음은 loss function 구현입니다.

 

y,yhat이 주어졌다는 가정하에 구현 해보겠습니다.

 
사진 삭제

사진 설명을 입력하세요.

def L1(y,yhat):
    loss=sum(abs(y-yhat))
    return loss
 
 
사진 삭제

사진 설명을 입력하세요.

다음 함수도 구현을 해보겠습니다.

def L2(yhat,y):
    x=yhat-y
    loss=np.dot(x,x)
    return loss
 

간단한 실습을 통해 그동안 배운 내용들을 구현 해보았습니다. 다시 개념 설명하는 글로 돌아오겠습니다.

 

반응형