donut

'시그모이드'에 해당되는 글 1건

  1. DNN_XOR구현

DNN_XOR구현

Tensorflow/DNN

 

 

 

DNN(Deep Neural Network)_XOR

이번 포스팅은 XOR알고리즘 구현 3탄입니다.
이미 지난번 포스팅에서 각각 분류함수1회, 분류함수3회를 사용하여 풀이를 해보았었는데요.
이번에는 분류함수 4회를 사용하여 풀이하는 포스팅을 진행하겠습니다.

 

모듈선언

In [23]:
import numpy as np
import tensorflow as tf
tf.random.set_seed(0)
print(tf.__version__)
 
2.1.0
 

XOR데이터 선언

In [24]:
x = [[0, 0],
    [0, 1],
    [1, 0],
    [1, 1]]
y = [[0],
    [1],
    [1],
    [0]]
 

학습시킬 dataset선언

In [25]:
#학습시킬 dataset 준비
dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(len(x))
In [26]:
#데이터 셋 확인
[i for i in dataset]
Out[26]:
[(<tf.Tensor: shape=(4, 2), dtype=int32, numpy=
  array([[0, 0],
         [0, 1],
         [1, 0],
         [1, 1]], dtype=int32)>,
  <tf.Tensor: shape=(4, 1), dtype=int32, numpy=
  array([[0],
         [1],
         [1],
         [0]], dtype=int32)>)]
 

전처리 함수

In [27]:
#형식을 플롯으로 맞춰준다.
#tf.cast는 2가지 사용법이 있다.
#tf.cast('조건') 일경우 참 거짓에 따라 1,0 반환
#그외에는 소수점 이하를 버림 해준다.
def preprocess_data(features, labels):
    features = tf.cast(features, tf.float32)
    labels = tf.cast(labels, tf.float32)
    return features, labels
In [46]:
preprocess_data(x,y)
Out[46]:
(<tf.Tensor: shape=(4, 2), dtype=float32, numpy=
 array([[0., 0.],
        [0., 1.],
        [1., 0.],
        [1., 1.]], dtype=float32)>,
 <tf.Tensor: shape=(4, 1), dtype=float32, numpy=
 array([[0.],
        [1.],
        [1.],
        [0.]], dtype=float32)>)
 

w,b 선언

In [37]:
#총 4번의 분류함수 사용을 위해 W,b를 4개씩 만들어준다.
#이때 메트릭스의 계산이 가능하도록 차원을 잘 설정 해줘야한다.
#ex) (2,1) * (1,1) = (2,1)
#    (3,2) * (2,2) = (3,2)
#xor은 (4,2) 임으로 (2,?)가 곱해져야함
W1 = tf.Variable(tf.random.normal((2, 10)), name='weight1')
b1 = tf.Variable(tf.random.normal((1,)), name='bias1')

W2 = tf.Variable(tf.random.normal((10, 10)), name='weight2')
b2 = tf.Variable(tf.random.normal((1,)), name='bias2')

W3 = tf.Variable(tf.random.normal((10, 10)), name='weight3')
b3 = tf.Variable(tf.random.normal((1,)), name='bias3')

W4 = tf.Variable(tf.random.normal((10, 1)), name='weight4')
b4 = tf.Variable(tf.random.normal((1,)), name='bias4')
 

hypothesis함수

In [38]:
#여러겹의 시그모이드 함수계산을 한다.
def deep_nn(features):
    layer1 = tf.sigmoid(tf.matmul(features, W1) + b1)
    layer2 = tf.sigmoid(tf.matmul(layer1, W2) + b2)
    layer3 = tf.sigmoid(tf.matmul(layer2, W3) + b3)
    hypothesis = tf.sigmoid(tf.matmul(layer3, W4) + b4)
    return hypothesis
In [39]:
#오차율 함수
def loss_fn(hypothesis, features, labels):
    cost = -tf.reduce_mean(labels * tf.math.log(hypothesis) + (1 - labels) * tf.math.log(1 - hypothesis))
    return cost
#정확도 함수
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(deep_nn(features),features,labels)
    return tape.gradient(loss_value, [W1, W2, W3, W4, b1, b2, b3, b4])
In [43]:
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
In [44]:
EPOCHS = 5000

for step in range(EPOCHS+1):
    for features, labels  in dataset:
        features, labels = preprocess_data(features, labels)
        grads = grad(deep_nn(features), features, labels)
        optimizer.apply_gradients(grads_and_vars=zip(grads,[W1, W2, W3,W4, b1, b2, b3, b4]))
        if step % 500 == 0:
            print("Iter: {}, Loss: {:.4f}".format(step, loss_fn(deep_nn(features),features,labels)))
 
Iter: 0, Loss: 0.6387
Iter: 500, Loss: 0.5629
Iter: 1000, Loss: 0.2864
Iter: 1500, Loss: 0.0466
Iter: 2000, Loss: 0.0176
Iter: 2500, Loss: 0.0100
Iter: 3000, Loss: 0.0068
Iter: 3500, Loss: 0.0051
Iter: 4000, Loss: 0.0040
Iter: 4500, Loss: 0.0033
In [51]:
#XOR에 대한 어큐러시 확인
x_data, y_data = preprocess_data(x, y)
test_acc = accuracy_fn(deep_nn(x_data),y_data)
print("Testset Accuracy: {:.4f}".format(test_acc))
 
Testset Accuracy: 1.0000
 

해당 포스팅은 부스트코스와,모두를위한 딥러닝 강의를 참고하여 작성하였습니다.

'Tensorflow > DNN' 카테고리의 다른 글

NN_XOR 구현  (0) 2020.08.08
Logistic_XOR 구현  (0) 2020.08.08