신경망 기울기


<aside>

import sys, os
sys.path.append(os.pardir)  # 부모 디렉터리의 파일을 가져올 수 있도록 설정
import numpy as np

# 소프트맥스 함수
def softmax(x):
    exp_x = np.exp(x - np.max(x))  # 오버플로우 방지
    return exp_x / np.sum(exp_x)

class simpleNet:
    def __init__(self):
        self.W = np.random.randn(2, 3)  # 정규분포로 초기화

    def predict(self, x):
        return np.dot(x, self.W)

    def loss(self, x, t):
        z = self.predict(x)
        y = softmax(z)
        return cross_entropy_error(y, t)

# 입력 데이터 및 정답 레이블
x = np.array([0.6, 0.9])
t = np.array([0, 0, 1])

# 신경망 객체 생성
net = simpleNet()

# 수치 미분을 적용한 손실 함수의 기울기 계산
f = lambda W: net.loss(x, t)
dW = numerical_gradient(f, net.W)

print(dW)

</aside>

기울기 함수


<aside>

# 기울기 구하는 함수
def numerical_gradient(f, x):
    h = 1e-4
    grad = np.zeros_like(x)

    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
    while not it.finished:
        idx = it.multi_index # 다차원 인덱스로 변환
        tmp_val = x[idx]

        # f(x+h)
        x[idx] = tmp_val + h
        fxh1 = f(x)

        # f(x-h)
        x[idx] = tmp_val - h
        fxh2 = f(x)

        # 기울기 계산
        grad[idx] = (fxh1 - fxh2) / (2 * h)

        # 원래 값 복원
        x[idx] = tmp_val
        it.iternext()

    return grad

TwoLayerNet


<aside>

class TwoLayerNet:
    def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
        #가중치 초기화
        self.params = {}
        
        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
        self.params['b2'] = np.zeros(output_size)
        
=> 
1. self.params - 딕셔너리로 초기화

2. self.params["key"] - 해당 key값으로 = ~ 값을 value로 랜덤한 가중치 값을 넣어줌
											- hidden_size만큼 0 값을 넣어줌

</aside>