AI/모두를 위한 딥러닝 정리
Day3. Gradient descent algorithm
reindeer002
2022. 3. 5. 21:36
728x90
만약 위와 같이 단순화시킨다면, dataset에 해당하는 W, cost(W)값은 아래와 같다.
W=0, 2의 cost값이 같은 이유는 cost함수가 아래와 같은 2차식이기 때문이다.
위와 같은 식에서 cost function의 최소값을 구하기 위해선 기울기가 0인 부분을 찾아야 한다.
이때 기울기가 0인 부분을 찾기 위해 사용하는 것이 경사하강법(Gradient descent algorithm)이다.
경사하강법의 특징은 아래와 같다.
- 주어진 cost function을 최소화하는데 사용함 - 많은 최소화 문제에 사용됨 - 주어진 cost function의 cost(W, b)에서 cost값을 최소화하는 W, b값을 찾아야 함 - 굉장히 많은 cost function을 최소화시킬 수 있는 알고리즘 |
경사하강법을 통해서 최소값을 찾는 방법은 다음과 같다.
1. 초기 추측값으로 시작한다. - 랜덤값에서 기울기를 구한다(0, 0). - W, b를 조금씩 바꿔가며 cost(W, b)값을 줄인다. 2. 파라미터를 바꿀 때마다 cost(W, b)를 감소시킬 가능성이 높은 쪽으로 변화시킨다. 3. 반복한다. 4. 최소화되는 부분에 수렴할 때까지 반복한다. |
이때, 랜덤값을 어디에서 시작하던지 간에 결국 최소값으로 수렴한다.
단, 주의해야할 점이 존재한다.
다음과 같이 왼쪽 식과 같은 경우 x값에 따라 최소값으로 이동하는 것이 2 군데로 나뉘기 때문에
올바른 값을 찾기 힘들다.
그러나 오른쪽 식과 같은 경우 최소값이 항상 한 군데로 수렴하기 때문에 문제가 없다.
이와 같은 함수를 convex function이라고 부른다.
import matplotlib.pyplot as plt
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
X = [1, 2, 3]
Y = [1, 2, 3]
W = tf.placeholder(tf.float32)
#simplification hypothesis
hypothesis = X * W
#make cost function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
W_val = []
cost_val = []
#move i between -3 to 5
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)
plt.plot(W_val, cost_val)
plt.show()
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
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_sum(tf.square(hypothesis - Y))
learning_rate = 0.1
#(W * X - Y) * X는 cost function을 미분했을 때 그 기울기를 의미함
gradient = tf.reduce_mean((W * X - Y) * X)
descent = W - learning_rate * gradient
update = W.assign(descent)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
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))
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
X = [1, 2, 3]
Y = [1, 2, 3]
#아무리 W값이 바뀌어도 동일한 결과를 도출함
W = tf.Variable(-3.0)
hypothesis = X * W
cost = tf.reduce_mean(tf.square(hypothesis - Y))
#shortcut
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1)
train = optimizer.minimize(cost)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(100):
print(step, sess.run(W))
sess.run(train)
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
X = [1, 2, 3]
Y = [1, 2, 3]
W = tf.Variable(5.)
hypothesis = X * W
#미분을 통해 구한 gradient
gradient = tf.reduce_mean((W*X - Y) * X) *2
cost = tf.reduce_mean(tf.square(hypothesis - Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1)
#자동으로 구한 gradient
gvs = optimizer.compute_gradients(cost)
apply_gradients = optimizer.apply_gradients(gvs)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(100):
#gradient와 gvs는 같을까?
print(step, sess.run([gradient, W, gvs]))
sess.run(apply_gradients)
주석에 유의하며 살펴볼 것
728x90