딥러닝 기초 (2) 역전파

딥러닝 기초 (2) 역전파

역전파 (BackPropagation)

Backpropagation 이라고 불리며, 순전파 SUM(node*weight)+bias 에서 나온 값을 토대로 오차(실제값 - 예측값)를 구한다. 편미분과 chain rule을 이용하여 가중치와 편향을 역방향으로 추적해서 노드 별로 수정 및 업데이트 하는 방법이다.

이 방법을 사용하면 loss를 최소화할 수 있다.

오차를 줄이는게 목표 >> 각각의 가중치가 경사가 하강하는 방향으로 향하게 해야한다.

>> 미분해서 (-) 방향으로 가게 한다.

Tensorflow & Keras 실습

지금까지 배운 내용들을 쉽게 구현할 수 있는 라이브러리들이 많다.

이번 실습에서는 Keras를 사용해서 간단한 신경망을 만들어보겠다.

예제 데이터는 Iris 데이터이다.

import pandas as pd import numpy as np import matplotlib.pyplot as plt # iris 꽃을 구분하기 위한 데이터 입니다. df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)

마지막 컬럼 4 는 Label이다. 학습 전에 분리해주겠다.

np.unique(df[4]) # array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object)

원활한 학습을 위해서 label들을 encoding 해준다.

X = df.drop(4, axis=1) y = df[4].replace('Iris-setosa',0).replace('Iris-versicolor',1).replace('Iris-virginica',2) print(np.unique(y)) # [0 1 2] X.shape, y.shape # ((150, 4), (150,))

Train set과 Test set을 나누어서 검증한다.

from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42) X_train.shape, X_test.shape # ((120, 4), (30, 4))

여기서부터 keras 라이브러리를 사용한다.

from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense model = Sequential() # 모델 인스턴스를 정의 num_of_column = 4 # [0, 1, 2, 3] first_hidden_layer = 200 second_hidden_layer = 100 output_layer = 3 # num of labels [0, 1, 2] # 신경망 모델 구조 정의 model.add(Dense(first_hidden_layer, input_dim=num_of_column, activation='relu')) model.add(Dense(second_hidden_layer, activation='relu')) model.add(Dense(output_layer, activation='softmax')) # 다중 분류 # 컴파일 단계, 옵티마이저와 손실함수, 측정지표를 연결해서 계산 그래프를 구성을 마무리 합니다. model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) results = model.fit(X_train, y_train, epochs=50, validation_data=(X_test, y_test))

best를 지정해주지 않으면 가장 마지막 줄에 있는 결과를 채택한다.

마지막으로 테스트 결과를 출력해준다.

test_loss, test_acc = model.evaluate(X_test, y_test, verbose=1) # 1/1 [==============================] - 0s 18ms/step - loss: 0.1140 - accuracy: 1.0000

학습 회차별 loss와 accuracy를 그래프로 그려서 확인한다.

# 그래프로 loss와 accuracy 확인 # 학습 횟수를 늘릴수록 좋은 학습 결과를 보인다 plt.plot(results.history['accuracy']) plt.plot(results.history['loss']) plt.title('The Increase of Epochs') plt.xlabel('Epochs') plt.ylabel('Range') plt.legend(['accuracy', 'loss'], loc = 'right') plt.show()

Epochs(학습 횟수)를 늘릴수록 좋은 학습 결과를 보인다.

간단한 모델을 만들어 보았는데, 다음 시간에는 더욱 복잡한 모델로 하이퍼 파라미터를 조정하는 방법을 알아보겠다.

from http://chal.tistory.com/20 by ccl(A) rewrite - 2021-08-16 04:00:35