블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

Linear Regression의 Tensorflow 실습 강좌를 정리해 본다. 





Hypothesis & Cost function (예측과 비용 함수)



학습을 통해 cost function의 W와 b를 minimized하는게 목적이다. 

- step-1: Node라는 operation 단위를 만든다. 

- step-2: Session.run을 통해 operation한다. 

- step-3: 결과값을 산출한다. 



Tensorflow는 W, b를 Variable로 할당한다. Variable이란 tensorflow가 변경하는 값이다라는 의미이다. 


H(x) 가설 구하기


$ python3

>>> import tensorflow as tf

>>> x_train = [1,2,3]

>>> y_train = [1,2,3]

>>> W = tf.Variable(tf.random_normal([1]), name='weight')

>>> b = tf.Variable(tf.random_normal([1]), name='bias')

>>> hypothesis = x_train * W + b


cost(W,b) 구하기

- reduce_mean: 전체 평균

- square: 제곱

>>> cost = tf.reduce_mean(tf.square(hypothesis - y_train))



minimize Cost 구하기

- GradienDescent 를 사용해서 minimize한다.

>>> optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

>>> train = optimizer.minimize(cost)





Graph 실행하기


Tensorflow의 Session을 만들고, 글로벌 변수값을 초기화 해준다. 

- 2000번을 돌리면서 20번만다 출력해 본다. 

- sess.run(train): 학습을 시킨다. 처음 Cost를 랜덤하게 가면서 학습할 수록 값이 작이진다. 

   sess.run(W): 1에 수렴하고

   sess.run(b): 작은 값이 수렴한다.

>>> sess = tf.Session()

>>> sess.run(tf.global_variables_initializer())

>>> for step in range(2001):

...     sess.run(train)

...     if step % 20 == 0:

...             print(step, sess.run(cost), sess.run(W), sess.run(b))

...

0 8.145951 [-0.13096063] [-0.43867812]

20 0.0741704 [0.87371004] [0.00051325]

40 0.0009571453 [0.9702482] [0.04034551]

   ... 생략 ...

1960 2.7972684e-08 [0.9998057] [0.00044152]

1980 2.5414716e-08 [0.99981487] [0.00042076]

2000 2.3086448e-08 [0.9998234] [0.00040107]


위의 train은 여러 Node가 연결된 graph가 된다. 






Placeholder로 수행하기


수행시 필요할 때 값을 동적으로 전달하여 train해 본다. 

- X, Y placeholder를 만든다. 

- feed_dict를 통해 값을 할당한다.

>>> X = tf.placeholder(tf.float32)

>>> Y = tf.placeholder(tf.float32)

>>> for step in range(2001):

...     cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict={X: [1,2,3], Y:[1,2,3]})

...     if step % 20 == 0:

...             print(step, cost_val, W_val, b_val)

...

0 2.3086448e-08 [0.9998238] [0.00040011]

20 2.0964555e-08 [0.99983215] [0.00038142]






참조


- 김성훈교수님의 Linear Regression의 Tensorflow 실습

- Github 실습 코드

posted by 윤영식