x_data = [1, 2, 3, 4, 5]
y_data = [1, 2, 3, 4, 5]
# 초기값은 임의로 지정할 수 있고, 실제 사용시에는 랜덤으로 지정하게 된다.
W = tf.Variable(2.9)
b = tf.Variable(0.5)
# hypothesis = W * x + b
hypothesis = W * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
# 에러 제곱의 평균으로 cost를 구하고 있다.
# tf.reduce_mean() : 평균
# tf.square() : 제곱
# learning_rate initialize
learning_rate = 0.01
# Gradient descent
with tf.GradientTape() as tape:
hypothesis = W * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
# GradientTape은 with와 함께 쓰인다.
# with 구문 안에 있는 변수(여기서는 W, b)들의 변화를 tape에다가 저장한다.
# 그리고 밑에서 tape의 gradient 메소드를 호출해서 경사도 값(= 미분값)을 구한다.
# gradient 메서드는 cost에 대한 변수들에 대한 개별 미분값(= 기울기 값)을 구해서 튜플로 반환한다.
W_grad, b_grad = tape.gradient(cost, [W, b])
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
# A.assign_sub(B) => A = A - B (= A -= B)
# learning_rate : 이 기울기 값(W_grad, b_grad)을 얼마만큼 반영할 것인지를 결정한다.
W = tf.Variable(2.9)
b = tf.Variable(0.5)
for i in range(100):
# Gradient descent
with tf.GradientTape() as tape:
hypothesis = W * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
W_grad, b_grad = tape.gradient(cost, [W, b])
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
if i % 10 == 0:
print("Step: {:5}\tW: {:10.4f}\tb: {:10.4f}\tcost: {:10.6f}".format(
i, W.numpy(), b.numpy(), cost.numpy()))
import tensorflow as tf
# Data
x_data = [1, 2, 3, 4, 5]
y_data = [1, 2, 3, 4, 5]
# W, b initialize
W = tf.Variable(2.9)
b = tf.Variable(0.5)
learning_rate = 0.01
print("\n")
for i in range(100) :
# Gradient descent
with tf.GradientTape() as tape:
hypothesis = W * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
W_grad, b_grad = tape.gradient(cost, [W, b])
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
if i % 10 == 0 :
print("Step: {:5}\tW: {:10.4f}\tb: {:10.4f}\tcost: {:10.6f}".format(i, W.numpy(), b.numpy(), cost.numpy()))
출처: 모두를 위한 딥러닝 강좌 2
https://www.youtube.com/watch?v=7eldOrjQVi0&list=PLQ28Nx3M4Jrguyuwg4xe9d9t2XE639e5C