AI 모델(딥러닝 기초)
-
4. 오차역전파법(2)AI 모델(딥러닝 기초)/4. 오차역전파법 2023. 1. 24. 11:19
이제 계산 그래프 이론으로만 이해했던 오차역전파법을 직접 구현해 볼 차례이다. ※ 덧셈 노드 계층 class AddLayer: def __init__(self): pass def forward(self, x, y): out = x + y return out def backward(self, dout): dx = dout * 1 dy = dout * 1 return dx, dy AddLayer라는 Class 형태로 덧셈 노드 계층을 구현할 수 있다. 순전파는 그대로를 보내고, 역전파도 그대로 아무것도 하지 않고 출력시키면 되기 때문에 초기화를 pass 시켰고, 순전파와 역전파 역시 우리가 오차역전파법(1)에서 그림으로 보았던 것처럼 그대로 출력을 시켜 주었다. ※ 곱셈 노드 계층 class MulLayer..
-
4. 오차역전파법(1)AI 모델(딥러닝 기초)/4. 오차역전파법 2023. 1. 20. 15:57
※ 오차역전파법(backpropagation) - 가중치 매개변수의 기울기를 효율적으로 계산하는 방법 1. 수식을 통한 설명 2. 계산 그래프를 통한 설명 ※ 계산 그래프 - 자료구조 Graph를 이용하여 노드와 에지를 사용하여 표현 순전파 : 계산 그래프(왼쪽 -> 오른쪽) 역전파 : 계산 그래프(오른쪽 -> 왼쪽) ■ 국소적 계산 - 전체에서 벌어지는 일과 상관없이 자신과 관계된 정보만으로 결과 출력이 가능함. - 중간 계산 결과를 모두 보관할 수 있음. - 역전파를 통해 '미분'을 효율적으로 계산 할 수 있음. 공부를 하는 교재의 그림을 참고하여 설명을 해보겠다. 순전파를 통해서 100원짜리 사과 2개를 산 후 소비세 10%가 붙을 때 지출하는 금액을 나타낼 수 있었다. 이를 역전파를 통해서 살펴보..
-
3. 신경망 학습(7)AI 모델(딥러닝 기초)/3. 신경망 학습 2023. 1. 15. 11:45
※ 미니배치 학습 구현 신경망 학습(6)을 통해 구현해 둔 TwoLayerNet class를 사용하여 MNIST 데이터셋을 미니배치로 구현해 보자. import numpy as np from dataset.mnist import load_mnist from two_layer_net import TwoLayerNet import matplotlib.pylab as plt # 데이터 읽기 (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 = 100..
-
3. 신경망 학습(6)AI 모델(딥러닝 기초)/3. 신경망 학습 2023. 1. 15. 10:56
전반적인 신경망에 대한 공부와 신경망학습에 대한 공부를 진행한 상태이기 때문에 간단한 2층 신경망의 학습 알고리즘을 구현해보자. ※ 신경망 학습의 기본단계 1. 미니배치 - 훈련 데이터 중 일부를 무작위로 가져와서 선별한 데이터, 미니배치의 손실함수를 줄이는 것이 최종 목표 2. 기울기 산출 - 각 가중치 매개변수의 기울기를 구하여 손실함수의 값을 가장 작게 하는 방향으로 손실함수를 줄인다.(최적값 찾기) 3. 매개변수 갱신 - 가중치 매개변수를 기울기 방향으로 조금씩 갱신한다. 4. 반복 - 1~3 과정을 계속해서 반복한다.(최적값을 구할 때까지, 즉 손실함수가 가장 작을 때 까지) ■ 확률적 경사 하강법 : 미니배치로 무작위로 골라낸 데이터에 대해 경사하강법으로 매개변수를 갱신하는 방법. 딥러닝 프레..
-
3. 신경망 학습(5)AI 모델(딥러닝 기초)/3. 신경망 학습 2023. 1. 10. 13:42
※ 신경망에서의 기울기 형상 2×3 행렬, 가중치 W, loss function이 L인 신경망을 생각해보자. 이와 같은 W 행렬을 통해 기울기를 구현해보면 이와 같은 편미분 행렬을 구해낼 수 있을 것이다. 여기서 1행 1번째 원소의 경우 w11을 변경했을 때 손실 함수 L이 얼마나 변화하느냐를 나타낸다. 또한, 미분을 적용한 행렬의 형상이 기존 W 행렬과 같은 2×3 행렬이라는 점을 알 수 있다. import sys, os sys.path.append(os.pardir) import numpy as np def softmax(a): c = np.max(a) exp_a = np.exp(a-c) sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return y def nu..
-
3. 신경망 학습(4)AI 모델(딥러닝 기초)/3. 신경망 학습 2023. 1. 9. 14:47
※ 기울기(Gradient) - 모든 변수의 편미분을 벡터로 정리한 것을 의미함 import numpy as np import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D def _numerical_gradient_no_batch(f, x): h = 1e-4 # 0.0001 grad = np.zeros_like(x) # x와 형상이 같은 배열을 생성 for idx in range(x.size): tmp_val = x[idx] # f(x+h) 계산 x[idx] = float(tmp_val) + h fxh1 = f(x) # f(x-h) 계산 x[idx] = tmp_val - h fxh2 = f(x) grad[idx] = (fxh1 - fx..
-
3. 신경망 학습(3)AI 모델(딥러닝 기초)/3. 신경망 학습 2023. 1. 7. 17:44
※ 수치 미분 일반적으로 우리는 미분 자체를 순간의 변화량으로 판단한다. 위와 같이 흔히 표현하며 이를 전방 차분이라고 부른다. 하지만, 코드로 위의 식을 구현할 때 몇 가지 고려할 점이 생긴다. 1. lim 표현을 위해 h를 아주 작은 값을 대입하는 방식을 사용하는데, 반올림 오차를 고려하여 이를 e^(-4) 정도로 하는 것이 적당하다. 2. x+h와 x 사이의 함수 f의 차분을 계산하는데, 이 계산에 오차가 존재한다. -> 진정한 미분은 x 위치의 함수의 기울기에 해당하지만 x+h와 x 사이의 차분을 계산하므로 오차가 발생함. 이 두가지 고려사항들을 통해 일반적으로 중심 차분 or 중앙 차분이라고 부르는 방식으로 코드를 구현한다. 이렇게 표현하는 미분 방식도 눈에 꽤 익숙할 것이다. 중앙 차분으로 코..
-
3. 신경망 학습(2)AI 모델(딥러닝 기초)/3. 신경망 학습 2023. 1. 7. 16:54
※ 미니 배치 학습 ■ 미니 배치 학습이란? - 훈련 데이터가 엄청나게 방대해 질 경우 데이터 일부를 추려서 학습시키고 전체의 근사치로 이용하는 방법 앞에서 사용했던 MNIST 데이터셋을 통해 미니 배치를 구현해보자. import sys, os sys.path.append(os.pardir) import numpy as np from dataset.mnist import load_mnist (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True) print(x_train.shape) print(t_train.shape) (60000, 784) (60000, 10) train_size = x_train.shap..