In [4]:
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
print(tf.__version__)


1.2.0

In [6]:
x_data = [1,2,3]
y_data = [1,2,3]

W = tf.Variable(tf.random_normal([1]), name = "weight")
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

hypothesis = W * X

In [11]:
#cost function을 정의 한다.
cost = tf.reduce_mean(tf.square(hypothesis - Y))

In [12]:
learning_rate = 0.1

#기울기를 구한다. 
#(W * X -Y) 는 hypothesis - Y랑 동일 하다. 
gradient = tf.reduce_mean((W * X - Y) * X)

#원래의 W에서 학습율을 곱한 기울기를 뺀다 
descent = W - learning_rate * gradient

#원래의 W에 적용한다. 
update = W.assign(descent)

In [13]:
sess = tf.Session()
sess.run(tf.global_variables_initializer())

In [15]:
for step in range(21):
    sess.run(update, feed_dict={X: x_data, Y: y_data})
    print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))


0 0.0254731 [ 0.92611825]
1 0.00724566 [ 0.96059644]
2 0.00206099 [ 0.97898477]
3 0.000586237 [ 0.98879188]
4 0.00016675 [ 0.99402237]
5 4.74307e-05 [ 0.99681193]
6 1.34907e-05 [ 0.99829972]
7 3.83733e-06 [ 0.99909317]
8 1.09165e-06 [ 0.99951637]
9 3.10383e-07 [ 0.99974209]
10 8.83158e-08 [ 0.99986243]
11 2.51149e-08 [ 0.99992663]
12 7.16112e-09 [ 0.99996084]
13 2.026e-09 [ 0.99997914]
14 5.78435e-10 [ 0.99998885]
15 1.65793e-10 [ 0.99999404]
16 4.69491e-11 [ 0.99999684]
17 1.29982e-11 [ 0.99999833]
18 3.62495e-12 [ 0.99999911]
19 1.06108e-12 [ 0.99999952]
20 2.65269e-13 [ 0.99999976]

In [ ]:
#텐서 플로에선 코스트 함수의 최소값을 위에처럼 일일히 구현하지 않아도 되는 기능을 제공하고 있다.
# optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
# train = optimizer.minimize(cost)