공부 기록
Deep Learning(0906_day2) - 2층 신경망 구현(수치미분 이용) 본문
신경망 학습¶
In [ ]:
from IPython.display import Image
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
In [ ]:
def cross_entropy_error(y, t):
delta = 1e-7
if y.ndim == 1:
y = y.reshape(1, y.size)
t = t.reshape(1, t.size)
batch_size = y.shape[0]
return -np.sum(t*np.log(y+delta)) / batch_size
- 신경망에서의 기울기
In [ ]:
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]
x[idx] = (tmp_val + h)
fxh1 = f(x) # f(x+h)
x[idx] = (tmp_val - h)
fxh2 = f(x) # f(x-h)
grad[idx] = (fxh1-fxh2) / (2*h)
x[idx] = tmp_val
it.iternext()
return grad
- softmax
In [ ]:
def softmax(x):
if x.ndim == 2:
x = x.T
x = x - np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x = x - np.max(x) # 오버플로 대책
return np.exp(x) / np.sum(np.exp(x))
- sigmoid
In [ ]:
def sigmoid(x):
return 1 / (1 + np.exp(-x))
- 2층 신경망 구현하기
In [ ]:
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) # 값 너무 커지는거 방지하려고 std곱해줌
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)
def predict(self, x): # 예측: 입력과 가중치 곱의 합을 함수에 통과시키는 과정
# 예측 구하기(가중치의 합 > sigmoid 통과 > 가중치의 합 > softmax 통과)
W1, W2 = self.params['W1'], self.params['W2']
b1, b2 = self.params['b1'], self.params['b2']
a1 = np.dot(x, W1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, W2) + b2
y = softmax(a2)
return y
def loss(self, x, t): # 예측과 정답의 차이
# 손실(비용)힘수의 결과 구하기
y = self.predict(x)
return cross_entropy_error(y, t)
def numerical_gradient(self, x, t):
# 수치 미분(중앙차분)
# 그레디언트(편미분의 벡터) 구하기
loss_W = lambda W : self.loss(x, t)
grads = {}
grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
return grads
In [ ]:
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
# 하이퍼파라미터 설정
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
train_loss_list = []
train_acc_list = []
test_acc_list = []
# 1에폭당 반복 수
iter_per_epoch = max(train_size / batch_size, 1)
for i in range(iters_num): # 경사하강법
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
grad = network.numerical_gradient(x_batch, t_batch) # 미분된 벡터
for key in ('W1', 'b1', 'W2', 'b2'):
network.params[key] = network.params[key] - (learning_rate * grad[key])
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
print(i, loss)
if i % iter_per_epoch == 0:
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("train acc, test acc | " + str(train_acc) + ", " + str(test_acc))
In [ ]:
'playdata' 카테고리의 다른 글
Deep Learning(0908_day4) (0) | 2021.09.08 |
---|---|
Deep Learning(0907_day3) - 2층 신경망 구현(오차역전파법 이용) (0) | 2021.09.07 |
Deep Learning(0906_day2) (0) | 2021.09.06 |
Deep Learning(0903_day1) (0) | 2021.09.03 |
Deep Learning(0902_day1) (0) | 2021.09.02 |
Comments