donut

'Tensorflow/DNN'에 해당되는 글 3건

  1. DNN_XOR구현
  2. NN_XOR 구현
  3. Logistic_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

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__)
 
2.1.0
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)))
 
Iter: 0, Loss: 1.0160
Iter: 500, Loss: 0.6482
Iter: 1000, Loss: 0.5609
Iter: 1500, Loss: 0.4236
Iter: 2000, Loss: 0.2926
Iter: 2500, Loss: 0.2021
Iter: 3000, Loss: 0.1465
Iter: 3500, Loss: 0.1120
Iter: 4000, Loss: 0.0895
Iter: 4500, Loss: 0.0739
 

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

In [ ]:
 

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

DNN_XOR구현  (0) 2020.08.12
Logistic_XOR 구현  (0) 2020.08.08

Logistic_XOR 구현

Tensorflow/DNN

 

 

 

 

NN(Neural Network)_XOR

NN(인공신경망)을 통해 컴퓨터가 사람의 뇌처럼
복잡한 계산을 할 수있게 한다.

대표적으로 XOR 알고리즘이 그 예다.
XOR은 아래 처럼, 주어진 두 수가 같은 경우에 1, 다를경우는 0을 출력한다. 즉 OR과 반대다.

XOR알고리즘을 풀기위해선 여러번의 여러번의 계산이 필요하다.
분류 함수로 한번에 할 수 없고, 분류 함수를 단계별로 진행해야 풀이가 가능하다.

이번 포스팅에서는 한번의 분류함수로 xor을 풀이해 보겠습니다.

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

XOR알고리즘을 tf코드로 모델 만들기

In [4]:
import numpy as np
import tensorflow as tf
print(tf.__version__)
 
2.1.0
In [5]:
#학습시킬 dataset 세팅
#배치값 미지정
dataset= tf.data.Dataset.from_tensor_slices((x,y))
In [6]:
#dataset값 확인
elem = [i for i in dataset]
print(elem)
print(len(elem))
 
[(<tf.Tensor: shape=(2,), dtype=int32, numpy=array([0, 0], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([0], dtype=int32)>), (<tf.Tensor: shape=(2,), dtype=int32, numpy=array([0, 1], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([1], dtype=int32)>), (<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 0], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([1], dtype=int32)>), (<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 1], dtype=int32)>, <tf.Tensor: shape=(1,), dtype=int32, numpy=array([0], dtype=int32)>)]
4
In [7]:
#학습시킬 dataset 세팅
#배치값 x의 길이로 설정
#배치는 한번에 학습시킬 size임
dataset= tf.data.Dataset.from_tensor_slices((x,y)).batch(len(x))
In [8]:
#dataset값 확인
elem = [i for i in dataset]
print(elem)
print(len(elem))
 
[(<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)>)]
1
 

전처리 함수(데이터 타입 맞추기)

In [10]:
def preprocess_data(features, labels):
    features = tf.cast(features, tf.float32)
    labels = tf.cast(labels, tf.float32)
    return features, labels
 

W, b 설정

In [11]:
#W,b의 초기값은 0이나 랜덤으로 으로 정해주면된다
#W = tf.Variable(tf.random.normal((2,1)))
#b = tf.Variable(tf.random.normal((1,)))
W = tf.Variable(tf.zeros((2,1)), name= 'weight')
b = tf.Variable(tf.zeros((1,)), name= 'bias')
print(W.numpy(), b.numpy())
 
[[0.]
 [0.]] [0.]
 

시그모이드 선언

In [12]:
def logistic_regression(features):
    hypothesis = tf.divide(1., 1. + tf.exp(tf.matmul(features, W) + b))
    return hypothesis
 

코스트 함수 선언

In [13]:
def loss_fn(hypothesis, features, labels):
    cost = -tf.reduce_mean(labels * tf.math.log(logistic_regression(features)) + (1-labels) * tf.math.log(1-hypothesis))
    return cost
#러닝레이트도 함께 선언
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
 

결과값 도출 함수 구현

시그모이드 함수로 도출된 hypothesis를 0 or 1로 cast해준다.

tf.cast => 조건이 참일경우 1, 거짓일 경우 0출력
tf.equal => 주어인 값이 같은경우 True, 다를경우 False
아래는 cast와 equal를 이해하기 쉽도록 예시를 작성 하였습니다.

In [14]:
test1 = 0.3
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[14]:
0.0
In [15]:
test1 = 0.6
test2 = tf.cast(test1 > 0.5,dtype = tf.float32)
test2.numpy()
Out[15]:
1.0
In [16]:
test1 = 0.6
test2 = 0.6
test3 = tf.equal(test1,test2)
test3.numpy()
Out[16]:
True
In [17]:
test7 = tf.cast(tf.equal(test1,test2),dtype = tf.float32)
test7.numpy()
Out[17]:
1.0
In [18]:
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
 

경사하강법

In [19]:
def grad(hypothesis, features, labels):
    with tf.GradientTape() as tape:
        loss_value = loss_fn(logistic_regression(features),features,labels)
    return tape.gradient(loss_value, [W,b])
 

실행

로지스틱 함수로 xor알고리즘을 완벽하게 구현하지 못했다.
loss값이 더이상 감소하지 않는 것을 확인 할 수 있었다.

In [23]:
EPOCHS = 1001

for step in range(EPOCHS):
    for features, labels  in dataset:
        features, labels = preprocess_data(features, labels)
        grads = grad(logistic_regression(features), features, labels)
        optimizer.apply_gradients(grads_and_vars=zip(grads,[W,b]))
        if step % 100 == 0:
            print("Iter: {}, Loss: {:.4f}".format(step, loss_fn(logistic_regression(features),features,labels)))
print("W = {}, B = {}".format(W.numpy(), b.numpy()))
 
Iter: 0, Loss: 0.6931
Iter: 100, Loss: 0.6931
Iter: 200, Loss: 0.6931
Iter: 300, Loss: 0.6931
Iter: 400, Loss: 0.6931
Iter: 500, Loss: 0.6931
Iter: 600, Loss: 0.6931
Iter: 700, Loss: 0.6931
Iter: 800, Loss: 0.6931
Iter: 900, Loss: 0.6931
Iter: 1000, Loss: 0.6931
W = [[0.]
 [0.]], B = [0.]
 

이 포스팅은 부스트코스 강의, 모두를위한 딥러닝 강의를 참고하였습니다.

In [ ]:
 

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

DNN_XOR구현  (0) 2020.08.12
NN_XOR 구현  (0) 2020.08.08