Numpy만으로 2층신경망짜기(DNN)
처음부터 하나씩 머릿 속으로 그리고 스케치하며 작동원리를 생각했다. tensor 차원을 다루는 방법을 알았으며 몇 가지 신기한 테크닉 또한 배웠다.
오차역전파를 통한 빠른 학습이 중앙차분으로 코딩한 미분보다 훨씬 빠른 것을 보고 굉장히 놀랬다.
풀어야 하는 궁금증 : Affine class에서 Bias를 나타내는 b를 보면 broad cast를 사용한다. mini_batch로 데이터를 받는다면 데이터 1개씩 차례대로 계산되는 것인지 (이게 맞는 것 같음) 아니면 200개를 한 번에 계산하는지 (이렇게 되면 bias가 broadcast 작동으로 공통의 bias를 공유하게 된다 데이터끼리) 알아봐야함.
entire code:
|
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# coding: utf-8 import numpy as np from collections import OrderedDict #--------------------functions--------------------- def identity_function(x): return x def step_function(x): return np.array(x > 0, dtype=np.int) def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_grad(x): return sigmoid(x) * (1.0 - sigmoid(x)) 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)) def mean_squared_error(y,t): return 0.5 * np.sum((y-t)**2) def cross_entropy_error(y,t): if y.ndim == 1: y = y.reshape(1,-1) t = t.reshape(1,-1) if t.size == y.size: t = t.argmax(axis=1) batch_size = y.shape[0] return -np.sum(np.log(y[np.arange(batch_size),t] + 1e-7)) / batch_size def softmax_loss(x,t): y = softmax(x) return cross_entropy_error(y,t) def _numerical_gradient_1d(f,x): h = 1e-4 grad = np.zeros_like(x) for idx in range(x.size): tmp_val = x[idx] x[idx] = float(tmp_val) + h f1 = f(x) x[idx] = tmp_val - h f2 = f(x) grad[idx] = (f1 - f2) / (2*h) x[idx] = tmp_val return grad def numerical_gradient_2d(f,X): if X.ndim == 1: return _numerical_gradient_1d(f,X) else: grad = np.zeros_like(X) for i,x in enumerate(X): grad[i] = _numerical_gradient_1d(f,x) return grad 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_value = x[idx] x[idx] = float(tmp_value) + h f1 = f(x) x[idx] = tmp_value - h f2 = f(x) grad[idx] = (f1 - f2) / (2*h) x[idx] = tmp_value it.iternext() return grad def mini_batch(x_train, y_train, batch_size=200): random_lenght = np.random.permutation(x_train.shape[0]) mod = x_train.shape[0] // float(batch_size) for idx in np.array_split(random_lenght,mod): x_batch, y_batch = x_train[idx], y_train[idx] yield x_batch, y_batch #----------------------------------layers-------------------------------- class Relu: def __init__(self): self.mask = None def forward(self,x): self.mask = (x <= 0) out = x.copy() out[self.mask] = 0 return out def backward(self,dout): dout[self.mask] = 0 dx = dout return dx class Sigmoid: def __init__(self): self.out = None def forward(self,x): out = sigmoid(x) self.out = out return out def backward(self,dout): dx = dout * self.out * (1.0 - self.out) return dx class Affine: def __init__(self,W,b): self.W = W self.b = b self.original_x_shape = None self.x = None self.dW = None self.db = None def forward(self,x): self.original_x_shape = x.shape x = x.reshape(x.shape[0],-1) self.x = x out = np.dot(self.x,self.W) + self.b return out def backward(self,dout): dx = np.dot(dout,self.W.T) self.dW = np.dot(self.x.T,dout) #여기가 이해가 안되네 self.db = np.sum(dout, axis=0) dx = dx.reshape(*self.original_x_shape) return dx class SoftmaxWithLoss: def __init__(self): self.y = None self.t = None self.loss = None def forward(self,x,t): self.y = softmax(x) self.t = t self.loss = cross_entropy_error(self.y,self.t) return self.loss def backward(self,dout=1): batch_size = self.t.shape[0] if self.y.size == self.t.size: dx = (self.y - self.t) / batch_size else: dx = self.y.copy() dx[np.arange(batch_size), self.t] -= 1 dx = dx / batch_size return dx class Dropout: def __init__(self, dropout_ratio=0.5): self.dropout_ratio = dropout_ratio self.mask = None def forward(self,x,train_flg=True): if train_flg: self.mask = np.random.rand(*x.shape) > self.dropout_ratio return x * self.mask else: return x * (1.0 - self.dropout_ratio) def backward(self,dout): return dout * self.mask #----------------------------------2층 신경망 구현-------------------------- 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) self.layers = OrderedDict() self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1']) self.layers['Relu'] = Relu() self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2']) self.last_layer = SoftmaxWithLoss() def predict(self,x): for layer in self.layers.values(): x = layer.forward(x) return x def loss(self,x,t): y = self.predict(x) return self.last_layer.forward(y,t) def accuracy(self,x,t): y = self.predict(x) y = np.argmax(y, axis=1) if t.ndim != 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 def gradient(self,x,t): self.loss(x,t) dout = 1 dout = self.last_layer.backward(dout) layers = list(self.layers.values()) layers.reverse() for layer in layers: dout = layer.backward(dout) grads = {} grads['W1'] = self.layers['Affine1'].dW grads['b1'] = self.layers['Affine1'].db grads['W2'] = self.layers['Affine2'].dW grads['b2'] = self.layers['Affine2'].db return grads #------------------------2층 신경망으로 mnist 학습하기------------------ from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() num = np.unique(y_train) num = num.shape[0] y_train = np.eye(num)[y_train] num = np.unique(y_test) num = num.shape[0] y_test = np.eye(num)[y_test] x_train = x_train / 255. x_test = x_test / 255. x_train = x_train.reshape(x_train.shape[0], -1) x_test = x_test.reshape(x_test.shape[0], -1) epoch_cycle = 20 batch_size = 200 learning_rate = 0.1 network = TwoLayerNet(input_size=784, hidden_size=300, output_size=10) for i in range(epoch_cycle): for x_batch, y_batch in mini_batch(x_train,y_train): grad = network.gradient(x_batch,y_batch) for key in ['W1','b1','W2','b2']: network.params[key] -= learning_rate * grad[key] if i % 5 == 0: train_acc = network.accuracy(x_train,y_train) test_acc = network.accuracy(x_test,y_test) print("train acc : ",train_acc) print("test acc : ", test_acc) |
result : 