{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 오차역전파법\n", "* 오차역전파법(backpropagation) : 가중치 매개변수의 기울기를 효율적으로 계산한다.\n", "* 수식\n", "* 계산그래프(시각적 이해)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 계산 그래프\n", "* 계산 그래프(computational graph) : 계산 과정을 그래프로 나타낸다. \n", "* 노드 node + 에지 edge(노드 사이 직선) 구성" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 계산 그래프로 풀다\n", "1. 현빈 군이 슈퍼에서 1개에 100원인 사과를 2개 샀다. 지불 금액은? 소비세 10% 부과된다. \n", "2. 현빈 군이 슈퍼에서 사과 2개, 귤 3개 샀다. 사과는 1개 100원, 귤은 1개 150원이고, 소비세 10%이다. 지불 금액은? \n", "\n", " * 순전파(forward propagation) : 계산을 왼쪽에서 오른쪽으로 진행한다. \n", " * 역전파(backward propagation) : 반대방향으로 계산한다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 국소적 계산\n", "* 계산 그래프 특징 : 국소적 계산을 전파하여 최종 결과를 얻는다. \n", "* 국소적 : 자신과 직접 관계된 작은 범위 \n", "* 국소적 계산 : 전체와 관련 없이 자신과 관계된 정보만 결과로 출력한다.(local, not global). \n", "\n", "![img](./deep_learning_images/fig_5-4.png)\n", "\n", "각 노드는 자신과 관련한 계산(두 숫자의 덧셈) 외에 아무것도 하지 않는다. \n", "계산 그래프는 국소적 계산에 집중한다. 각 노드의 국소적 계산 결과를 전달하여 전체를 구성한다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 왜 계산 그래프로 푸는가?\n", "* 계산 그래프를 사용하는 가장 큰 이유 \n", "역전파를 통해 **미분**을 효율적으로 계산한다. \n", "![img](./deep_learning_images/fig_5-5.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 연쇄법칙\n", "연쇄법칙(chain rule) : 국소적 미분을 전달하는 원리\n", "### 계산 그래프의 역전파\n", "$$y = f(x)$$\n", "![img](./deep_learning_images/fig_5-6.png)\n", "### 연쇄법칙이란?\n", "* 합성 함수 : 여러 함수로 구성된 함수 \n", "* 연쇄법칙은 합성 함수의 미분에 대한 성질 \n", "_합성 함수의 미분은 합성 함수를 구성하는 각 함수의 미분의 곱으로 나타낼 수 있다._ \n", "\n", "$${\\partial z \\over \\partial x} = {\\partial z \\over \\partial t} {\\partial t \\over \\partial x}$$\n", "* 예시\n", "$$ z = t^2 \\\\ t = x + y$$\n", "### 연쇄법칙과 계산 그래프\n", "* 연쇄법칙 계산을 계산 그래프로 나타낸다. 2제곱 계산은 **2로 나타낸다.\n", "![img](./deep_learning_images/fig_5-7.png) \n", "\n", "* 역전파가 하는 일은 연쇄 법칙의 원리와 같다. \n", "* 그림에 국소적 미분(편미분) 값을 대입하면 다음과 같다.\n", "![img](./deep_learning_images/fig_5-8.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 역전파\n", "### 덧셈 노드의 역전파\n", "### 곱셈 노드의 역전파\n", "### 사과 쇼핑의 예" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 단순한 계층 구현하기\n", "### 곱셈 계층" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class MulLayer:\n", " def __init__(self):#x, y 초기화\n", " self.x = None\n", " self.y = None\n", " \n", " def forward(self, x, y):\n", " self.x = x\n", " self.y = y\n", " out = x*y\n", " \n", " return out\n", " \n", " def backward(self, dout):\n", " dx = dout * self.y # x, y 바꾸기\n", " dy = dout * self.x\n", " \n", " return dx, dy" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "220.00000000000003\n" ] } ], "source": [ "#사과 쇼핑 구현하기\n", "\n", "apple = 100\n", "apple_num = 2\n", "tax = 1.1\n", "\n", "# 계층들\n", "mul_apple_layer = MulLayer()\n", "mul_tax_layer = MulLayer()\n", "\n", "# 순전파\n", "apple_price = mul_apple_layer.forward(apple, apple_num)\n", "price = mul_tax_layer.forward(apple_price, tax)\n", "\n", "print(price)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.2 110.00000000000001 200\n" ] } ], "source": [ "# 각 변수의 미분은 backward()\n", "dprice = 1\n", "dapple_price, dtax = mul_tax_layer.backward(dprice)\n", "dapple, dapple_num = mul_apple_layer.backward(dapple_price)\n", "\n", "print(dapple, dapple_num, dtax)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![img](./deep_learning_images/fig_5-16.png)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# 덧셈 계층\n", "class AddLayer:\n", " def __init__(self):\n", " pass# 초기화 필요 없어서 아무것도 하지 말라는 명령이다!\n", " \n", " def forward(self, x, y):\n", " out = x + y\n", " return out\n", " \n", " def backward(self, dout):\n", " dx = dout * 1\n", " dy = dout * 1\n", " return dx, dy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![img](./deep_learning_images/fig_5-17.png)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "715.0000000000001\n", "110.00000000000001 2.2 165.0 3.3000000000000003 650\n" ] } ], "source": [ "# 사과 2개, 오렌지 3개 구매\n", "apple = 100\n", "apple_num = 2\n", "orange = 150\n", "orange_num = 3\n", "tax = 1.1\n", "\n", "#계층들\n", "mul_apple_layer = MulLayer()\n", "mul_orange_layer = MulLayer()\n", "add_apple_orange_layer = AddLayer() # 덧셈 노드\n", "mul_tax_layer = MulLayer() # 곱셈 노드\n", "\n", "# 순전파\n", "apple_price = mul_apple_layer.forward(apple, apple_num)\n", "orange_price = mul_orange_layer.forward(orange, orange_num)\n", "all_price = add_apple_orange_layer.forward(apple_price, orange_price)\n", "price = mul_tax_layer.forward(all_price, tax)\n", "\n", "# 역전파\n", "dprice = 1\n", "dall_price, dtax = mul_tax_layer.backward(dprice)\n", "dapple_price, dorange_price = add_apple_orange_layer.backward(dall_price)\n", "\n", "dorange, dorange_num = mul_orange_layer.backward(dorange_price)\n", "dapple, dapple_num = mul_apple_layer.backward(dapple_price)\n", "\n", "print(price)\n", "print(dapple_num, dapple, dorange_num, dorange, dtax)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 활성화 함수 계층 구현하기\n", "### ReLU 계층\n", "![img](./deep_learning_images/fig_5-18.png)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "class Relu:\n", " def __init__(self):\n", " self.mask = None # mask : True/False 구성된 넘파이 배열\n", " \n", " def forward(self, x):\n", " self.mask = (x <= 0) # 0보다 작은 인덱스 True, 0보다 크면 False 유지\n", " out = x.copy() #x 값을 복제한다. 원본 파일 변경을 방지한다.\n", " out[self.mask] = 0\n", " \n", " return out\n", " \n", " def backward(self, dout):\n", " dout[self.mask] = 0\n", " dx = dout\n", " \n", " return dx" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1. -0.5]\n", " [-2. 3. ]]\n" ] } ], "source": [ "import numpy as np\n", "#mask 알아보기\n", "x = np.array([[1.0, -0.5], [-2.0, 3.0]])\n", "print(x)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[False True]\n", " [ True False]]\n" ] } ], "source": [ "mask = (x <= 0)\n", "print(mask)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sigmoid 계층\n", "$$ y = {1 \\over {1 + \\exp(-x)}}$$\n", "* 계산 그래프(순전파)\n", "![img](./deep_learning_images/fig_5-19.png) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "계산 그래프(역전파)의 단계별 흐름" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "# 시그모이드 계층\n", "class Sigmoid:\n", " def __init__(self):\n", " self.out = None\n", " \n", " def forward(self, x):\n", " out = 1 / (1+np.exp(-x))\n", " self.out = out\n", " \n", " return out\n", " \n", " def backward(Self, dout):\n", " dx = dout * (1.0 - self.out) * self.out\n", " \n", " return dx" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Affine/Softmax 계층 구현하기\n", "### Affine 계층" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(2,)\n", "(2, 3)\n", "(3,)\n" ] } ], "source": [ "X = np.random.rand(2)\n", "W = np.random.rand(2,3)\n", "B = np.random.rand(3)\n", "\n", "print(X.shape)\n", "print(W.shape)\n", "print(B.shape)\n", "\n", "Y = np.dot(X, W) + B" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* 어파인 변환(affine transformation) : 신경망의 순전파 때 수행하는 행렬의 곱\n", "* 어파인 계층 : 어파인 변환을 수행하는 처리" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 배치용 Affine 계층" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 0, 0, 0],\n", " [10, 10, 10]])" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X_dot_W = np.array([[0,0,0], [10,10,10]])\n", "B = np.array([1,2,3])\n", "\n", "X_dot_W" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 1, 2, 3],\n", " [11, 12, 13]])" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X_dot_W + B" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[1, 2, 3],\n", " [4, 5, 6]])" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dY = np.array([[1,2,3], [4,5,6]])\n", "dY" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([5, 7, 9])" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dB = np.sum(dY, axis = 0) # 편향의 역전파는 그 두 데이터에 대한 미분을 데이터마다 더해서 구현한다.\n", "dB" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "class Affine:\n", " def __init__(self, W, b):\n", " self.W = W\n", " self.b = b\n", " self.x = None\n", " self.dW = None\n", " self.db = None\n", " \n", " def forward(self, x):\n", " self.x = x\n", " out = np.dot(x, self.W) + self.b\n", " \n", " return out\n", " \n", " def backward(self, dout):\n", " dx = np.dot(dout, self.W.T)\n", " self.dW = np.dot(Self.x.T, dout)\n", " self.db = np.sum(dout, axis = 0)\n", " \n", " return dx" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Softmax with Loss 계층\n", "출력층에서 사용하는 소프트맥스 함수" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "#Softmax with loss 구현\n", "\n", "class SoftmaxWithLoss:\n", " def __init__(self):\n", " self.loss = None\n", " self.y = None\n", " self.t = None\n", " \n", " def forward(self, x, t):\n", " self.t = t\n", " self.y = softmax(x)\n", " self.loss =cross_entropy_error(self.y, self.t)\n", " return self.loss\n", " \n", " def backward(self, dout = 1):\n", " batch_size = self.t.shape[0]\n", " dx = (self.y - self.t) / batch_size\n", " \n", " return dx" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 오차역전파법 구현하기\n", "### 신경망 학습의 전체 그림\n", "### 오차역전파법을 적용한 신경망 구현하기\n", "TwoLayerNet 클래스 인스턴스 변수\n", "1. params\n", " * 딕셔너리 변수, 신경망의 매개변수를 보관\n", " \n" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "import sys, os\n", "sys.path.append(os.pardir)\n", "import numpy as np\n", "from common.layers import *\n", "from common.gradient import numerical_gradient\n", "from collections import OrderedDict\n", "\n", "class TwoLayerNet:\n", " \n", " def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):\n", " \n", " # 가중치 초기화\n", " self.params = {}\n", " self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)\n", " self.params['b1'] = np.zeros(hidden_size)\n", " self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)\n", " self.params['b2'] = np.zeros(output_size)\n", " \n", " # 계층 생성\n", " self.layers = OrderedDict()\n", " self.layers['Affine'] = Affine(self.params['W1'], self.params['b1'])\n", " self.layers['Relu1'] = Relu()\n", " self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])\n", " \n", " self.lastLayer = SoftmaxWithLoss()\n", " \n", " def predict(self, x):\n", " for layer in self.layers.values():\n", " x = layer.forward(x)\n", " \n", " return x\n", " \n", " #x 입력 데이터, t 정답 레이블\n", " def loss(self, x, t):\n", " y = self.predict(x)\n", " return self.lastLayer.forward(y, t)\n", " \n", " def accuracy(self, x, t):\n", " y = self.predict(x)\n", " y = np.argmax(y, axis = 1)\n", " if t.ndim != 1 : t = np.argmax(t, axis=1) # 파이썬 기초문법 참고\n", " \n", " accuracy = np.sum(y == t) / float(x.shape[0])\n", " return accuracy\n", " \n", " def numerical_gradient(self, x, t):\n", " loss_W = lambda W: self.loss(x, t)\n", " \n", " grads = {}\n", " grads['W1'] = numerical_gradient(loss_W, self.params['W1'])\n", " grads['b1'] = numerical_gradient(loss_W, self.params['b1'])\n", " grads['W2'] = numerical_gradient(loss_W, self.params['W2'])\n", " grads['b2'] = numerical_gradient(loss_W, self.params['b2'])\n", " return grads\n", " \n", " def gradient(self, x, t):\n", " # 순전파\n", " self.loss(x, t)\n", " \n", " # 역전파\n", " dout = 1\n", " dout = self.lastLayer.backward(dout)\n", " \n", " layers = list(self.layers.values())\n", " layers.reverse()\n", " for layer in layers:\n", " dout = layer.backward(dout)\n", " \n", " # 결과를 저장한다.\n", " grads = {}\n", " grads['W1'] = self.layers['Affine1'].dW\n", " grads['b1'] = self.layers['Affine1'].db\n", " grads['W2'] = self.layers['Affine2'].dW\n", " grads['b2'] = self.layers['Affine2'].db\n", " \n", " return grads # 기울기가 반환된다.\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 오차역전파법으로 구한 기울기 검증하기\n", "* 기울기 확인(gradient check)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "W1:2.08360027012189e-10\n", "b1:1.0034358459090229e-09\n", "W2:7.089479214632267e-08\n", "b2:1.417670533840343e-07\n" ] } ], "source": [ "import sys, os\n", "sys.path.append(os.pardir) #부모디렉터리 설정\n", "import numpy as np\n", "from dataset.mnist import load_mnist\n", "from two_layer_net import TwoLayerNet\n", "\n", "# 데이터 읽기\n", "(x_train, t_train), (x_test, t_test) = load_mnist(normalize= True, one_hot_label= True)\n", "\n", "network = TwoLayerNet(input_size = 784, hidden_size= 50, output_size= 10)\n", "\n", "x_batch = x_train[:3]\n", "t_batch = t_train[:3]\n", "\n", "grad_numerical = network.numerical_gradient(x_batch, t_batch)\n", "grad_backprop = network.gradient(x_batch, t_batch)\n", "\n", "# 각 가중치 차이의 절댓값을 구하고, 그 절댓값의 평균을 낸다.\n", "for key in grad_numerical.keys():\n", " diff = np.average( np.abs(grad_backprop[key] - grad_numerical[key]))\n", " print(key + \":\" + str(diff))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* 수치 미분과 오차역전파법으로 구한 기울기의 차이가 매우 작은 것을 알 수 있다. \n", "(= 정확한 기울기를 구한 것이다.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 오차역전파법을 사용한 학습 구현하기" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "훈련 정확도 : 0.10218333333333333\n", "시험 정확도: 0.101\n", "훈련 정확도 : 0.7876333333333333\n", "시험 정확도: 0.7922\n", "훈련 정확도 : 0.87525\n", "시험 정확도: 0.8785\n", "훈련 정확도 : 0.89895\n", "시험 정확도: 0.8996\n", "훈련 정확도 : 0.9072333333333333\n", "시험 정확도: 0.908\n", "훈련 정확도 : 0.9135833333333333\n", "시험 정확도: 0.9151\n", "훈련 정확도 : 0.9190833333333334\n", "시험 정확도: 0.9197\n", "훈련 정확도 : 0.9226666666666666\n", "시험 정확도: 0.9232\n", "훈련 정확도 : 0.9266333333333333\n", "시험 정확도: 0.9282\n", "훈련 정확도 : 0.9307\n", "시험 정확도: 0.9305\n", "훈련 정확도 : 0.9325166666666667\n", "시험 정확도: 0.933\n", "훈련 정확도 : 0.9357\n", "시험 정확도: 0.9362\n", "훈련 정확도 : 0.93775\n", "시험 정확도: 0.938\n", "훈련 정확도 : 0.9399666666666666\n", "시험 정확도: 0.9388\n", "훈련 정확도 : 0.94225\n", "시험 정확도: 0.9408\n", "훈련 정확도 : 0.9449833333333333\n", "시험 정확도: 0.9427\n", "훈련 정확도 : 0.94585\n", "시험 정확도: 0.9434\n" ] } ], "source": [ "import sys, os\n", "sys.path.append(os.pardir)\n", "import numpy as np\n", "from dataset.mnist import load_mnist\n", "from two_layer_net import TwoLayerNet\n", "\n", "# data load\n", "(x_train, t_train), (x_test, t_test) = load_mnist(normalize= True, one_hot_label=True)\n", "network = TwoLayerNet(input_size = 784, hidden_size = 50, output_size = 10)\n", "\n", "iters_num = 10000\n", "train_size = x_train.shape[0]\n", "batch_size = 100\n", "learning_rate = 0.1\n", "\n", "train_loss_list = []\n", "train_acc_list = []\n", "test_acc_list = []\n", "\n", "iter_per_epoch = max(train_size / batch_size, 1) # 에폭당 반복\n", "\n", "for i in range(iters_num):\n", " batch_mask = np.random.choice(train_size, batch_size)\n", " x_batch = x_train[batch_mask]\n", " t_batch = t_train[batch_mask]\n", " \n", " # 오차역전파법으로 기울기 구하기\n", " grad = network.gradient(x_batch, t_batch)\n", " \n", " # 갱신\n", " for key in ('W1', 'b1', 'W2', 'b2'):\n", " network.params[key] -= learning_rate * grad[key]\n", " \n", " loss = network.loss(x_batch, t_batch)\n", " train_loss_list.append(loss)\n", " \n", " if i % iter_per_epoch == 0:\n", " train_acc = network.accuracy(x_train, t_train)\n", " test_acc = network.accuracy(x_test, t_test)\n", " train_acc_list.append(train_acc)\n", " test_acc_list.append(test_acc)\n", " print(\"훈련 정확도 : \" + str(train_acc))\n", " print(\"시험 정확도: \" + str(test_acc))\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 정리\n", "\n", "* 이번 장에서 배운 내용\n", " * 계산 그래프를 이용하면 계산 과정을 시각적으로 파악 가능\n", " * 계산 그래프의 노드는 국소적 계산으로 구성한다. 국소적 계산을 조합해서 전체 계산을 구한다.\n", " * 계산 그래프의 순전파는 일반적인 계산이고, 역전파는 각 노드의 미분을 구한다.\n", " * 신경망의 구성 요소를 계층으로 구현하여 기울기를 효율적으로 계산한다.(오차역전파법).\n", " * 수치 미분과 오차역전파법의 결과를 비교하여 구현에 잘못이 없는지 확인 가능(기울기 확인)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }