Deep Learning (Deep Neural Network)
손실값은 0에 가까울수록 좋다.
손실값을 적게 만들기 위한 알고리즘들이 존재한다.
And/ Or는 잘 되지만, Xor는 계산이 잘 안되는 경향.
역산 해 가면서 보정 해 주는 알고리즘의 개발 이후 Xor 문제도 해결되었다.
뉴럴 네트워크는 인간의 뇌를 모방해서 만들어진 알고리즘이다.
눈으로 보면 뇌에서 계산이 된다.
Input Signal이 들어오면 수상돌기를 통해서 데이터가 들어오고, 결과가 넘어오면 새로운 뉴런으로 아웃풋/인풋 된다.
임계치를 지나가야 활성화되는 Activation Function이 있다.
뇌의 구조를 알고리즘으로 구현한 것이 뉴럴 네트워크 알고리즘이다.
Neural Network 구성요소
- 임계치 (threshold) : 어떤 값이 활성화되기 위한 최소값
- 가중치 (weight) : w
- 바이어스 (bias) : b
- 뉴런값/net/가설값 (hypothesis) : 입력값과 가중치 곱의 합
- 활성함수 (activation function) : 임계치보다 작으면 0, 크면 1을 출력하는 함수 (f)
- 뉴런 (neuron)
w와 b의 값을 찾아내는 것이 머신러닝.
Neural Network Architecture
single layer perception
input layer > output layer
x_data = [[14.0, 80., 73.],
[18., 88., 95.],
[16., 91., 90.],
[20., 98., 100.],
[14., 66., 70.]]
y_data = [[110.], [131.], [129.], [143.], [98.]]
#set tensorflow Sequential model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=1, input_dim = 3))
model.add(tf.keras.layers.Activation('linear'))
#set optimizer and learning method
sgd = tf.keras.optimizers.SGD(learning_rate=1e-5)
model.compile(loss = 'mse', optimizer = sgd)
#train the model : call fit()
history = model.fit(x_data, y_data, epochs=100)
모듈 준비 및 데이터 초기화
import tensorflow as tf
x_data = [[14.0, 80., 73],
[18., 88., 95.],
[16, 91, 90],
[20, 98, 100],
[14, 66, 70]]
y_data = [[110.], [131.], [129], [143.],[98.]]
tensorflow 모델 생성 및 단층 퍼셉트론 구성
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=1, input_dim=3, activation='linear'))
옵티마이저 및 손실함수 설정
sgd = tf.keras.optimizers.SGD(learning_rate=1e-5)
model.compile(loss='mse', optimizer=sgd)
학습 진행
history = model.fit(x_data, y_data, epochs=100)
Predict
y_predict = model.predict([[14, 93, 90]])
print(y_predict)
손실률 분석
import matplotlib.pyplot as plt
plt.plot(history.history['loss'])
plt.title('Simple model')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['loss'], loc='upper right')
plt.show()
Multilayer perception = Deep learning Network
x_data = [[0, 0], [0, 1], [1, 0], [1, 1]]
y_data = [[0], [1], [1], [0]]
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=2, input_dim=2, activation='sigmoid'))
model.add(tf.keras.layers.Dense(units=1, input_dim=2, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.SGD(learning_rate=1),
metrics=['accuracy'])
history = model.fit(x_data, y_data, epochs=500)
Activation functions : 활성화 함수
Supervise Learning (지도 학습)
정답 Lable이 있는 것.
정답을 알려주며 학습한다.
유형
- Regression
- Binary classification
- Multi-label classification
Classification
0 or 1로 구분된다.
- Spam Detection : Spam or Ham
- Facebook feed : Show or Hide
- Credit Card Fraudulent Transaction detection : legitimate/fraud
Logistic Classification
Hypothesis
가설값이 1보다 크거나 0보다 작은 값을 줄 수도 있는 문제가 있다.
0~1 사이의 값으로 만들어주는 처리가 필요하다 : Sigmoid function이 적합하다.
필요한 모듈 import : tensorflow, numpy
import tensorflow as tf
import numpy as np
tf.random.set_seed(777)
Keras 모델 준비
# Training Data
x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]
y_data = [[0], [0], [0], [1], [1], [1]]
#Keras Sequential model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=1, input_dim=2))
model.add(tf.keras.layers.Activation('sigmoid'))
Optimizer와 손실함수 설정
sgd = tf.keras.optimizers.SGD(lr = 0.01)
model.compile(loss='binary_crossentropy', optimizer = sgd, metrics=['accuracy'])
#print summary
model.summary()
Train the model
history = model.fit(x_data, y_data, epochs=100)
Accuracy report
print("Accuracy : ", history.history['accuracy'][-1])
Predict and Evaluate
y_predict = model.predict(x_data)
result = tf.cast(y_predict > 0.5, dtype=tf.float32)
evaluate = model.evaluate(x_data, y_data)
print(y_predict)
print(result.numpy())
print("loss : {} , accuracy : {}".format(evaluate[0], evaluate[1]))
'대학생활 > 수업' 카테고리의 다른 글
레벨디자인심화 10주차 - 던전 컨셉과 데이터 (0) | 2023.11.16 |
---|---|
리얼타임엔진 11주차 - Verse 튜토리얼2 (0) | 2023.11.14 |
게임밸런스및시뮬레이션 10주차 - 반복문과 배열 (0) | 2023.11.13 |
게임그래픽프로그래밍심화 10주차 (0) | 2023.11.13 |
게임기획과비주얼스크립팅 9주차 - UMG, UI (0) | 2023.11.09 |