본문 바로가기

카테고리 없음

[Tensorflow #4] cost 최소화

이 내용은 Sung kim님의 강의를 바탕으로 만들어졌습니다.
tensorflow 2.x 버전이 2019년 12월에 나왔다고 합니다. 아래의 코드는 1.x버전입니다.

%pylab inline
import tensorflow as tf
import matplotlib.pyplot as plt

X = [1,2,3]
Y = [1,2,3]

W = tf.placeholder(tf.float32)
# Our hypothesis for linear model X * W
hypothesis = X * W

# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Launch the graph in a session
sess = tf.Session()
# Initalizes global variables in the graph.
sess.run(tf.global_variables_initializer())
# Variables for plotting cost function

W_val = []
cost_val = []
for i in range(-30, 50):
    feed_W = i * 0.1
    curr_cost, curr_W = sess.run([cost, W], feed_dict={W:feed_W})
    W_val.append(curr_W)
    cost_val.append(curr_cost)

# Show the cost function
plt.plot(W_val, cost_val)
matplotlib.pyplot.show()

위의 코드를 실행하면 -3부터 5까지의 값을 0.1 단위로 cost 공식에 대입해 가며 cost를 확인한다.
따라서 사람이 그래프를 보고 가장 cost가 작아지는 지점을 확인할 수 있고 List를 확인하여 최저점을 찾을 수 있으나, 비효율적이라는 문제가 있다.

  • reduce_mean(input_tensor, axis) : axis번째 차원을 없애기 위해 mean(평균)방식을 사용한다. axis를 넣지 않으면 평균 값 리턴

  • W.assign(value) : W에 value를 assign함.

    %pylab inline
    import tensorflow as tf                                          
    import matplotlib.pyplot as plt
    
%pylab inline
import tensorflow as tf                                          
import matplotlib.pyplot as plt

X_data = [1,2,3]
Y_data = [1,2,3]

#with tf.device('/device:GPU:0'):
W = tf.Variable(tf.random_normal([1]), name='weight')
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# Our hypothesis for linear model X * W
hypothesis = X * W

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

# Minimize: Gradient Descent using derivative: W -= learning_rate * derivative
learning_rate = 0.001
gradient = tf.reduce_mean((W*X-Y)*X)
descent = W-learning_rate * gradient
update = W.assign(descent)


# Launch the graph in a session
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Initalizes global variables in the graph.
sess.run(tf.global_variables_initializer())
# Variables for plotting cost function
res = []

for step in range(2001):
    sess.run(update, feed_dict={X:X_data, Y:Y_data})
    res.append([step, sess.run(cost, feed_dict={X:X_data, Y:Y_data}), sess.run(W)])
print(res)

따라서 Gradient Descent 알고리즘은 임의로 W를 정하여 각 회차마다 W를 변화시켜가며 cost가 0에 최대한 가까운 W를 찾아낸다.