이번 시간에는 기존의 머신러닝과 다르게 '스스로 학습할 수 있도록 만드는 신경망'인 딥러닝을 학습했고, 이를 이해하기 위해 OR게이트와 XOR게이트를 구현해봤다.
#라이브러리 임포트
import tensorflow as tf
tf.random.set_seed(777) # 똑같은 데이터 셋을 활용할 수 있도록 고정
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.losses import mse
#데이터 준비하기
data = np.array([[0,0], [1,0], [0,1], [1,1]])
label = np.array([[0],[1],[1],[1]])
model = Sequential()
model.add(Dense(1, input_shape=(2,), activation='linear')) # -> 단층 퍼셉트론
model.compile(optimizer=SGD(), loss=mse, metrics=['acc'])
history = model.fit(data, label, epochs=500)
import matplotlib.pyplot as plt
his_dict = history.history
loss = his_dict['loss']
epochs = range(1, len(loss) + 1)
fig = plt.figure(figsize = (10, 5))
# 훈련 및 검증 손실 그리기
ax1 = fig.add_subplot(1, 2, 1)
# 가로 한줄 세로 두줄로 그릴 건데 얘는 첫번째 차트야
ax1.plot(epochs, loss, color = 'orange', label = 'train_loss')
ax1.set_title('train loss')
ax1.set_xlabel('epochs')
ax1.set_ylabel('loss')
ax1.legend()
acc = his_dict['acc']
# 훈련 및 검증 정확도 그리기
ax2 = fig.add_subplot(1, 2, 2)
# 가로 한줄 세로 두줄로 그릴 건데 얘는 두번째 차트야
ax2.plot(epochs, acc, color = 'blue', label = 'train_accuracy')
ax2.set_title('train accuracy')
ax2.set_xlabel('epochs')
ax2.set_ylabel('accuracy')
ax2.legend()
plt.show()
#데이터 준비하기
data = np.array([[0,0], [1,0], [0,1], [1,1]])
label = np.array([[0],[1],[1],[0]])
#모델 구성, 설정 및 학습하기
xor0_model = Sequential()
xor0_model.add(Dense(1, input_shape=(2,), activation='linear'))
xor0_model.compile(optimizer=SGD(), loss=mse, metrics=['acc'])
history = xor0_model.fit(data, label, epochs=500)
import matplotlib.pyplot as plt
his_dict = history.history
loss = his_dict['loss']
epochs = range(1, len(loss) + 1)
fig = plt.figure(figsize = (10, 5))
# 훈련 및 검증 손실 그리기
ax1 = fig.add_subplot(1, 2, 1)
ax1.plot(epochs, loss, color = 'orange', label = 'train_loss')
ax1.set_title('train loss')
ax1.set_xlabel('epochs')
ax1.set_ylabel('loss')
ax1.legend()
acc = his_dict['acc']
# 훈련 및 검증 정확도 그리기
ax2 = fig.add_subplot(1, 2, 2)
ax2.plot(epochs, acc, color = 'blue', label = 'train_accuracy')
ax2.set_title('train accuracy')
ax2.set_xlabel('epochs')
ax2.set_ylabel('accuracy')
ax2.legend()
plt.show()
#데이터 준비하기
data = np.array([[0,0], [1,0], [0,1], [1,1]])
label = np.array([[0],[1],[1],[0]])
from tensorflow.keras.optimizers import RMSprop
xor_model = Sequential()
xor_model.add(Dense(32, input_shape=(2,), activation='relu')) # input층이면서 첫번째 레이어
xor_model.add(Dense(1, activation='sigmoid'))
# 첫번째 층에서 입력받아서 출력해주는 두번째 레이어 결과를 한개만 낼 것이라서 1 입력
xor_model.compile(optimizer=RMSprop(), loss=mse, metrics=['acc'])
# 손실점수는 mean square error를 사용
history = xor_model.fit(data, label, epochs=100)
#학습결과 차트 그리기
import matplotlib.pyplot as plt
his_dict = history.history
loss = his_dict['loss']
epochs = range(1, len(loss) + 1)
fig = plt.figure(figsize = (10, 5))
# 훈련 및 검증 손실 그리기
ax1 = fig.add_subplot(1, 2, 1)
ax1.plot(epochs, loss, color = 'orange', label = 'train_loss')
ax1.set_title('train loss')
ax1.set_xlabel('epochs')
ax1.set_ylabel('loss')
ax1.legend()
acc = his_dict['acc']
# 훈련 및 검증 정확도 그리기
ax2 = fig.add_subplot(1, 2, 2)
ax2.plot(epochs, acc, color = 'blue', label = 'train_accuracy')
ax2.set_title('train accuracy')
ax2.set_xlabel('epochs')
ax2.set_ylabel('accuracy')
ax2.legend()
plt.show()