In [4]:
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
print(tf.__version__)
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))
In [ ]:
#텐서 플로에선 코스트 함수의 최소값을 위에처럼 일일히 구현하지 않아도 되는 기능을 제공하고 있다.
# optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
# train = optimizer.minimize(cost)