본문 바로가기

프로그래밍/AI:ML:DL

[Tensorfow] 초간단 회귀모형 변형

반응형

Sung Kim 교수의 모두의 딥러닝 강의 중 간단한 선형회귀모델을 텐서플로우 코드로 구하는 예제를 따라해 보고,

hypothesis 모델의 식을 예제의 1차식 (직선) 에서 2차 다항식으로 바꾸어 돌려봄. 트레이닝에 사용하는 데이터도 y = x*x 에 가까운 값을 주어 보았음.

잘 구해짐. 하지만, 트레이닝 데이터를 얼토당토않은 랜덤한 값을 주면, 트레이닝 하면서 쉽게 발산해 버리는 듯 하다. 3차 다항식 모델도 역시 잘 발산하는 듯 하다.

import tensorflow as tf

x = tf.placeholder(tf.float32, shape=[None])
y = tf.placeholder(tf.float32, shape=[None])

w2 = tf.Variable(tf.random_uniform([1]), name="weight2") 
w1 = tf.Variable(tf.random_uniform([1]), name="weight1") 
b = tf.Variable(tf.random_uniform([1]), name="bias")

#              3 
# H(x) =  w2 x   + w1  x +  b 
# 

hypothesis = w2*x*x + w1*x + b # 2차 다항식 모델 
cost = tf.reduce_mean(tf.square(hypothesis - y)) 
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) 
train = optimizer.minimize(cost)

sess = tf.Session() 
sess.run(tf.global_variables_initializer())

for i in range(2001): 
    cost_, w2_, w1_, b_, _ = sess.run([cost, w2, w1, b, train], 
                                      feed_dict={x:[-2, -1, 0, 1, 2 ], y:[4.1, 1, 0, 1.1, 4.3 ]}) 
    if i%200 == 0: 
        print(i, 'cost=', cost_, 'w2=', w2_, 'w1=', w1_, 'b=', b_) 

sess.run(hypothesis, feed_dict={x:[1., 2., 3., 4., 5.]})

728x90