[딥러닝 학습3] Gradient descent algorithm
제작된 모델이 아래와 같은 경우 유사한 결과를 도출한다고 보장받기 어렵다.

cost function 모양이 아래와 같은 convex function과 같아야 어디서 시작되던 비슷한 결과를 보장한다고 볼 수 있다.

Cost Function을 만들때 반드시 Convex Function과 같은 모양을 하고있는지 확인하여야 한다.
matplotlib 설치. http://matplotlib.org/users/installing.html
메뉴얼대로 했을때는 잘 안되서 아래와 같이 삭제하고 su 계정에서 설치하니 정상으로 설치되었다.
pip3 uninstall matplotlib python3 -mpip uninstall matplotlib sudo su pip3 install matplotlib python3 -mpip install -U matplotlib
import tensorflow as tf
import matplotlib.pyplot as plt
X = [1,2,3]
Y = [1,2,3]
W = tf.placeholder(tf.float32)
hypothesis = X * W
cost = tf.reduce_mean(tf.square(hypothesis - Y))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
W_val = []
cost_val = []
for i in range(-30, 50):
feed_W = i * 0.1 #-3 ~ 5까지 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)
plt.plot(W_val, cost_val)
plt.show()
이런 결과로, 최적의 W=1 을 찾았음.
수동으로 Gradient descent 알고리즘 구현하기
import tensorflow as tf
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 = X * W
cost = tf.reduce_mean(tf.square(hypothesis - Y))
#optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
#train = optimizer.minimize(cost)
#위와 아래는 같은 코드. 직접 미분으로 구현하는 코드.
learning_rate = 0.1
gradient = tf.reduce_mean((W * X - Y) * X)
descent = W - learning_rate * gradient
update = W.assign(descent)
#그라디언트 수정하고싶을떄??
#gvs = optimizer.compute_gradients(cost) #그라디언트 계산
#gvs = gvs-1 #그라디언트 수정
#apply_gradients = otimizer.apply_gradients(gvs)#그라디언트 적용
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(20):
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))
결과를 보면 Cost가 0에 가깝고 W가 1에 가깝게 수렴하는 것을 확인할 수 있다.
0 2.75116 [ 0.23218885] 1 0.782552 [ 0.59050071] 2 0.222593 [ 0.78160036] 3 0.0633152 [ 0.88352019] 4 0.0180097 [ 0.93787742] 5 0.00512274 [ 0.96686798] 6 0.00145713 [ 0.98232961] 7 0.000414473 [ 0.99057579] 8 0.000117892 [ 0.99497378] 9 3.35337e-05 [ 0.99731934] 10 9.5389e-06 [ 0.99857032] 11 2.71296e-06 [ 0.99923754] 12 7.715e-07 [ 0.99959338] 13 2.19523e-07 [ 0.9997831] 14 6.24761e-08 [ 0.99988431] 15 1.77528e-08 [ 0.99993831] 16 5.05179e-09 [ 0.9999671] 17 1.42888e-09 [ 0.99998248] 18 4.09781e-10 [ 0.99999064] 19 1.16984e-10 [ 0.99999499]
이 포스트는 김성훈 교수님의 ‘모두의 딥러닝’ 강의를 학습하며 정리한 노트입니다.

최근 댓글