머신러닝

3-11 2차 및 3차 다항식 Hypothesis에 의한 XOR 논리 처리

coding art 2021. 7. 2. 19:41
728x90

2종류의 출력 결과를 주는 quadratic_regression 기법을 개선하기 위해서 2차 다항식 polynomial hypothesis 설정을 hypothesis_0에서 hypothesis_1로 아래와 같이 변경 설정해 보기로 하자.

hypothesis_0 경우는 50% 이상 해를 주고 있으나 엄연히 hypothesis 값이 0.5 인 경우가 출력된다. 따라서 hypothesis_1처럼 2차식 형태에서 다항식 차수를 증가시킨 3차식 형태를 테스트해보자. 사용하는 정보량에서는 두 경우가 차이가 없으나 차수가 하나 추가되었다.

 

코드를 실행해 보면 랜덤 변수에 의한 초기 값 설정이 잘못 된 경우 다음과 같이 nan 이 나오는 경우를 제외하고는 100% 제대로 된 결과를 출력함을 알 수 있다.

nan 이 나오는 원인은 랜덤 변수에 의한 초기치 설정과 learning rate 값이 맞물려 cost 함수에 대한 gradientdescent 적용이 발산하게 되는 원인을 제공한다. random_normal 의한 초기 값이 1.0 을 벗어나 버리게 되면 이런 현상이 주로 발생하므로 랜덤 넘버 생성을 random_uniform default로 변경하도록 한다. random_uniform default[0, 1.0) 사이의 랜덤 값을 생성한다. random_normal을 그대로 사용할 경우에는 표준 편차를 0.01 로 아주 작은 값을 부여하면 해결이 가능하다.

 

hypothesis_1을 사용하면 10번 실행 모두 다 성공적인 결과를 출력한다. 바이아스 1b1 만을 사용하는 linear regression 과 비해 하나는 바이아스 값이 0 인 경우와 또 다른 하나는 바이아스 b2 인 경우가 곱해짐에 따라 XOR 문제의 해가 제대로 출력된다.

 

바이아스 0.0 도 아예 랜덤 넘버 b0 로 대체하는 경우에는 nan hypothesis 0.5 인 결과들이 섞여 나온다. 3차 다항식 예제는 다음의 파이선 소스 파일에서 #처리된 hypothesis를 교체하여 사용하도록 하자.

 

#quadratic_regression_XOR_bias_01.py

import tensorflow as tf
tf.set_random_seed(777)  

x1_data = [0., 1., 0., 1.]
x2_data = [0.,0.,1.,1.]
y_data = [0., 1., 1., 0.]

#placeholders for a tensor that will be always fed.
x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

#w1 = tf.Variable(tf.random_normal([1]), name='weight1')
#w2 = tf.Variable(tf.random_normal([1]), name='weight2')
#b1 = tf.Variable(tf.random_normal([1]), name='bias1')
#b2 = tf.Variable(tf.random_normal([1]), name='bias2')

w1 = tf.Variable(tf.random_uniform([1]), name='weight1')
w2 = tf.Variable(tf.random_uniform([1]), name='weight2')
b0 = tf.Variable(tf.random_uniform([1]), name='bias0')
b1 = tf.Variable(tf.random_uniform([1]), name='bias1')
b2 = tf.Variable(tf.random_uniform([1]), name='bias2')

#one more bias added
hypothesis = (x1 * w1 + x2 * w2 )*(x1 * w1 + x2 * w2 + b2)
#hypothesis = (x1 * w1 + x2 * w2 + b1)*(x1 * w1 + x2 * w2 + b2)
#hypothesis =(x1 * w1 + x2 * w2)*(x1 * w1 + x2 * w2+ b1)* (x1 * w1 + x2 * w2 + b2)

#cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))

#Minimize. Need a very small learning rate for this data set
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.05)
train = optimizer.minimize(cost)

#Launch the graph in a session.
sess = tf.Session()
#Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())

for step in range(5001):
    cost_val, hy_val, _ = sess.run([cost, hypothesis, train],
                                   feed_dict={x1: x1_data,x2: x2_data, Y: y_data})
    if step % 100 == 0:
        print(step, cost_val, hy_val,sess.run(w2),sess.run(b2),sess.run(w1),sess.run(b1))