본문 바로가기

Deep Learning & AI/AI

(딥러닝_온라인)쉽게 배우는 역전파 학습법 _ 역전파 학습법 코드

참고) 해당 포스팅은 패스트 캠퍼스 100% 환급 챌린지 미션 기록용 포스팅이며, 강좌 내용에 맞추어 포스팅함을 언급

 

클립명 : PART4)딥러닝의 3 STEP의 기초

           쉽게 배우는 역전파 학습법 (STEP 2) - 역전파 학습법을 이용한 심층 신경망 학급 - 1

          쉽게 배우는 역전파 학습법 (STEP 2) - 학습법의 수식적 이해 - 1

          쉽게 배우는 역전파 학습법 (STEP 2) - 학습법의 수식적 이해 - 2

본 포스팅은 역전파 학습법 코드를 살펴볼 것이며, 2번의 포스팅으로 나누겠다

 


"""
역전파 학습법을 이용한 심층 신경망 학습
"""
#%%
import time
import numpy as np
#%% 유틸리티 함수

def _t(x):
    return np.transpose(x)

def m(A, B):
    return np.matmul(A, B)

#%% Sigmoid 구현

class Sigmoid:
    def __init__(self):
        self.last_o = 1
    
    def __call__(self, x):
        self.last_o = 1 / (1.0 + np.exp(-x))
        return self.last_o
    
    def grad(self): # Sigmoid(x)(1 - sigmoid(x))
        return self.last_o * (1 - self.last_o)
#%% Mean Squared Error 구현

class MeanSquaredError:
    def __init__(self):
        # gradient
        self.dh = 1
        self.last_diff = 1
        
    def __call__(self, h, y): # 1/2 * mean((h-y)^2)
        self.last_diff = h - y
        return 1/2 * np.mean(np.square(h-y))
    
    def grad(self): # h - y
        return self.last_diff

#%% 뉴런 구현

class Neuron:
    def __init__(self, W, b, a_obj):
        # Model Parameter
        self.W = W
        self.b = b
        self.a = a_obj()
        
        # gradient
        self.dW = np.zeros_like(self.W)
        self.db = np.zeros_like(self.b)
        self.dh = np.zeros_like(_t(self.W))
        
        self.last_x = np.zeros((self.W.shape[0]))
        self.last_h = np.zeros((self.W.shape[1]))
        
    def __call__(self, x):
        self.last_x = x
        self.last_h = _m(_t(self.W), x) + self.b
        return self.a(self.last_h)
    
    def grad(self): # dy/dh = W
        return self.W * self.a.grad()
    
    def grad_W(self, dh):
        grad = np.ones_like(self.W)
        grad_a = self.a.grad()
        for j in range(grad.shape[1]): #dy/ dw = x
            grad[:, j] = dh[j] * grad_a[j] * self.last_x
        return grad
    
    def grad_b(self, dh): # dy/dh = 1
        return dh * self.a.grad() * 1
#%% 심층 신경망
class DNN:
    def __init__(self, hidden_depth, num_neuron, input, output, activation=Sigmoid):
        def init_var(i, o):
            return np.random.normal(0.0, 0.01, (i, o)), np.zeros((o,))

        self.sequence = list()
        # First hidden layer
        W, b = init_var(input, num_neuron)
        self.sequence.append(Neuron(W, b, activation))

        # Hidden Layers
        for index in range(hidden_depth):
            W, b = init_var(num_neuron, num_neuron)
            self.sequence.append(Neuron(W, b, activation))

        # Output Layer
        W, b = init_var(num_neuron, output)
        self.sequence.append(Neuron(W, b, activation))

    def __call__(self, x):
        for layer in self.sequence:
            x = layer(x)
        return x

    def calc_gradient(self, loss_obj):
        # TODO
 

(글자수 : 2000자 이상)

강의 소개 링크 : bit.ly/3cx6kMd

 

딥러닝/인공지능 올인원 패키지 Online. | 패스트캠퍼스

Tensorflow2.0부터 Pytorch까지 딥러닝 대표 프레임워크를 정복하기. 생활 깊숙이 침투한 인공지능, 그 중심엔 딥러닝이 있습니다. 가장 강력한 머신러닝의 툴로서 주목받는 딥러닝은 생각보다 어려

fastcampus.co.kr