NN_XOR 구현
Tensorflow/DNN
NN(Neural Network)_XOR¶
이번 포스팅은 지난번 XOR문제를 한번의 분류함수로 풀이한 포스팅과 이어지는 내용입니다.
이번에는 여러번의 logistic함수를 중첩해서 문제를 해결하게됩니다.
지난번과 동일한 데이터를 사용합니다.
In [1]:
import numpy as np
import tensorflow as tf
tf.random.set_seed(0)
print(tf.__version__)
In [4]:
#XOR데이터를 세팅해준다
x = [[0, 0],
[0, 1],
[1, 0],
[1, 1]]
y = [[0],
[1],
[1],
[0]]
In [5]:
#학습시킬 dataset 준비
dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(len(x))
#전처리를 위한 함수 준비(데이터형식을 맞춰줌)
def preprocess_data(features, labels):
features = tf.cast(features, tf.float32)
labels = tf.cast(labels, tf.float32)
return features, labels
In [6]:
#총 3번의 분류함수 사용을 위해 W,b를 3개씩 만들어준다.
W1 = tf.Variable(tf.random.normal((2, 1)), name='weight1')
b1 = tf.Variable(tf.random.normal((1,)), name='bias1')
W2 = tf.Variable(tf.random.normal((2, 1)), name='weight2')
b2 = tf.Variable(tf.random.normal((1,)), name='bias2')
W3 = tf.Variable(tf.random.normal((2, 1)), name='weight3')
b3 = tf.Variable(tf.random.normal((1,)), name='bias3')
In [7]:
#뉴럴 넷 함수 설정
#총 3번의 시그모이드 함수를 적용시키게됨
#1,2계층에서 사용하여 얻은 시그모이드 값을
#3계층에서 한번더 시그모이드를 적용한다.
def neural_net(features):
layer1 = tf.sigmoid(tf.matmul(features, W1) + b1)
layer2 = tf.sigmoid(tf.matmul(features, W2) + b2)
layer3 = tf.concat([layer1, layer2],-1)
layer3 = tf.reshape(layer3, shape = [-1,2])
hypothesis = tf.sigmoid(tf.matmul(layer3, W3) + b3)
return hypothesis
In [8]:
#오차율, 정확도, 경사하강법 함수 설정
def loss_fn(hypothesis, labels):
cost = -tf.reduce_mean(labels * tf.math.log(hypothesis) + (1 - labels) * tf.math.log(1 - hypothesis))
return cost
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
def accuracy_fn(hypothesis, labels):
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, labels), dtype=tf.float32))
return accuracy
def grad(hypothesis, features, labels):
with tf.GradientTape() as tape:
loss_value = loss_fn(neural_net(features),labels)
return tape.gradient(loss_value, [W1, W2, W3, b1, b2, b3])
In [9]:
#지난번 1회의 분류함수로 적용했을땐
#loss가 감소하지않고 일정했는데
#뉴럴넷, 즉 계층 별 계산을 통해 로스가 감소하는걸 확인 가능했다.
EPOCHS = 5000
for step in range(EPOCHS):
for features, labels in dataset:
features, labels = preprocess_data(features, labels)
grads = grad(neural_net(features), features, labels)
optimizer.apply_gradients(grads_and_vars=zip(grads,[W1, W2, W3, b1, b2, b3]))
if step % 500 == 0:
print("Iter: {}, Loss: {:.4f}".format(step, loss_fn(neural_net(features),labels)))
해당포스팅은 부스트코스 강의와, 모두를위한 딥러닝 강의를 참고하였습니다.
In [ ]:
'Tensorflow > DNN' 카테고리의 다른 글
DNN_XOR구현 (0) | 2020.08.12 |
---|---|
Logistic_XOR 구현 (0) | 2020.08.08 |