선형회귀 (Linear Regression) 기본 소스코드 분석
원본 소스 출처 : https://github.com/hunkim/DeepLearningZeroToAll/blob/master/lab-02-3-linear_regression_tensorflow.org.py
import tensorflow as tf # Model parameters W = tf.Variable([.3], tf.float32) b = tf.Variable([-.3], tf.float32) # Model input and output x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) linear_model = x * W + b # cost/loss function loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares # optimizer optimizer = tf.train.GradientDescentOptimizer(0.01) train = optimizer.minimize(loss) # training data x_train = [1, 2, 3, 4] y_train = [0, -1, -2, -3] # training loop init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) # reset values to wrong for i in range(1000): sess.run(train, {x: x_train, y: y_train}) # evaluate training accuracy curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train}) print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))
한줄 한줄 살펴보면,
import tensorflow as tf
tensorflow 라이브러리를 import 하여 tf로 약칭을 정한다. (이후로 tf 라고 타이핑한다면 tensorflow 라이브러리를 사용할 수 있도록 만든다.)
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32)
linear_model = x * W + b
이는, 선형 회귀의 그래프를 그릴 수 있는 방정식이며, 뒤에서 주어지는 x_train 값을 넣었을때의 계산 결과 Y가 뒤에서 주어질 y_train 값과 일치하는 횟수가 가장 많은 최적의 W값과 b값을 구하기 위해 만든다.
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
loss라는 변수를 만들고, tensorflow 내장함수인 reduce_sum 함수와 square 함수를 이용하여 손실함수를 할당한다.
square는 제곱이며, 학습되어 예상된 Y값과 정답으로 주어진 Y값의 오차를 구해 제곱한 뒤 reduce_sum 함수로 값들을 모두 더한다.
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
x_train = [1, 2, 3, 4] y_train = [0, -1, -2, -3]
init = tf.global_variables_initializer()
sess = tf.Session() sess.run(init) # reset values to wrong
for i in range(1000): sess.run(train, {x: x_train, y: y_train})
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
for문을 빠져나왔으면 (학습이 n번 완료되었으면), curr_w 변수와 curr_b 변수, curr_loss 변수를 각각 만들어,
curr_w 에는 학습 후 최적이라 판단된 W 의 값,
curr_b 에는 학습 후 최적이라 판단된 b의 값,
curr_loss 에는 학습 후 최적이라 판단된 최후의 오차값을 할당한다.
print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))
최적의 값들을 출력해 본다.
실제 출력 결과이다.
W 는 -1에 수렴하고있으며, b는 1에 수렴하고 있다. loss는 매우 적게 표시됨을 확인 할 수 있다.