M.L (p.137)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import numpy as np from p88func import * import sys,os sys.path.append(os.pardir) from mnist import load_mnist 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) def predict(self,x): 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 accuracy(self,x,t): y = self.predict(x) y = np.argmax(y,axis=1) t = np.argmax(t,axis=1) accuracy = np.sum(y == t) / float(x.shape[0]) return accuracy 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 net = TwoLayerNet(input_size=784, hidden_size=100, output_size=10) print(net.params['W1'].shape) print(net.params['b1'].shape) print(net.params['W2'].shape) print(net.params['b2'].shape) x = np.random.randn(100,784) y = net.predict(x) x = np.random.randn(100,784) t = np.random.randn(100,10) grads = net.numerical_gradient(x,t) print(grads['W1'].shape) print(grads['b1'].shape) print(grads['W2'].shape) print(grads['b2'].shape) |
2층 신경망을 하나의 클래스로 구현한 것이다.
class name은 TwoLayerNet으로 구성요소를 하나씩 알아보자.
- def __init__함수로 input_size, hidden_size, output_size, weight_init_std=0.01로 초기화한다. self.params로 W1,b1,W2,b2 (weight,bias) 을 입력값에 따라 초기화한다.
- def_predict 함수는 초기화된 weight,bias 를 가지고 입력데이터를 정답데이터와 형태가 맞게 변화시킨다.
- def_loss 는 cross_entropy_error를 사용하여 정답레이블과 입력레이블의 loss 값을 구한다.
- def_accuracy는 정확도를 구하는 함수로 변화된 입력데이터와 정답레이블의 최대 값 인덱스가 동일한지 판단하여 개수를 세어 x 개수로 나누어 확률적으로 변환시킨다.
- def_numerical_gradient 함수는 각각의 weight, bias 값들이 loss 값에 얼마나 영향을 미치는지에 대한 편미분 값을 나타낸다.
TwoLayerNet 입력값에 대한 값들
편미분한 값들이 weight, bias 값들에 각각 대응한다.