본문 바로가기

대외활동/ABC 지역주도형 청년 취업역량강화 ESG 지원산업

[ABC 220927] 신경망

반응형

신경망

  • 퍼셉트론(Perceptron)
    • 여러 개의 신호를 입력으로 받아 하나의 값을 출력
    • x는 입력, y는 출력, w는 가중치
    • x와 가중치 w를 곱한 값을 모두 더하여 하나의 값(y)로 만들어냄
    • 이때, 임곗값(threshold)과 비교하여 크면 1, 그렇지 않으면 0을 출력
      • → 활성화 함수(Activation Function)
      • → 위에서 사용한 것은 계단 함수(Step Function)

신경망 : OR 게이트 문제

  • tf.random.set_seed(777)
    • 실험의 재생산성
  • Dense 층
    • 퍼셉트론 생성
    • 밀집층, 다층 퍼셉트론, 완전 연결층 등
  • Dense(1, input_shape = (2,))
    • 두 개의 특성을 가지는 1차우너 데이터를 입력으로 받고, 한 개의 출력을 가지는 Dense 층
    • '1'은 퍼셉트론의 개수 또는 은닉 유닉(hidden unit)이라고 표현

OR_gate 구현하기

문제 정의 : OR 게이트 구현 00 => 0  /  01 => 1  /  10 => 1  /  11 => 1

데이터 준비하기

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

# 데이터 준비하기
X = np.array([[0,0], [1,0], [0,1], [1,1]])
y = np.array([[0],[1],[1],[1]])
X.shape

X

모델 구성하기

model = Sequential()
model.add(Dense(1, input_shape=(2,), activation='linear')) # dense 층 몇개인지, input 몇개 넣을건지, 결정할 때 뭘로 결정할거냐
# 단층 퍼셉트론

모델 설정하기

model.compile(optimizer=SGD(), loss=mse, metrics=['acc']) # metrics는 그냥 출력 안해도 나오긴 함

모델 학습하기

history = model.fit(X, y, epochs=500) # 학습데이터, 정답, 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()

XOR 게이트 구현하기

XOR 게이트 00 => 0  /  01 => 1  /  10 => 1  /  11 => 0

데이터 준비하기

from tensorflow.keras.optimizers import RMSprop
# 데이터 준비하기
X = np.array([[0,0], [1,0], [0,1], [1,1]]) # X1과 X2가 다르면 1, 같으면 0
y = np.array([[0],[1],[1],[0]])

모델 구성하기 / 모델 설정하기

xor_model = Sequential()
xor_model.add(Dense(32, input_shape=(2,), activation='relu')) # dense 층 몇개인지, input 몇개 넣을건지, 결정할 때 뭘로 결정할거냐
# 단층 퍼셉트론
xor_model.add(Dense(1, activation='sigmoid'))
xor_model.compile(optimizer=RMSprop(), loss=mse, metrics=['acc']) # metrics는 그냥 출력 안해도 나오긴 함

모델 학습하기

xor_history = xor_model.fit(X, y, epochs=500) # 학습데이터, 정답, 500번 공부

학습 결과 그려보기

import matplotlib.pyplot as plt

his_dict = xor_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()

AND / XOR 게이트

  • AND 게이트
    • 둘 다 참일 때만, 참을 결과로 출력하는 연산
    • 모든 입력값이 1일 때만 1을 출력

  • XOR 게이트
    • 둘 중 하나일 때, 참을 결과로 출력하는 연산
    • 입력값이 같지 않으면 1을 출력

반응형