본문 바로가기

Deep Learning

Linear Regression의 Hypothesis와 cost

x y
1 1
2 2
3 3

위의 traning data set은 아래의 그래프처럼 나타낼 수 있다.

 

Linear Hypothesis

H(x) = Wx + b 라는 가설을 세울 때,

위의 그래프는 W = 1, b = 0이 가장 실제 데이터와 가깝다고 할 수 있다.

 

Cost Function (Loss Function)

: 가설과 실제 데이터가 얼마나 다른가? 그 차이를 계산하는 함수.

 

(H(x) - y)^2

 

H(x) : 가설로 예측한 값

y : 실제의 값

H(x) - y : 값의 차이

 

위 값에 제곱을 하는 이유?

: 차이를 양수로 표현해주고, 차이가 클 때 penalty를 많이 줄 수 있음.

 

cost 값을 구하는 공식 (m:데이터 개수)

H(x) = Wx + b를 식에 대입하면 결국 W와 b를 이용하여 cost function의 값을 줄일 수 있다.

목표는 cost가 가장 작은 W, b를 구하는 것 !

이러한 값을 최소화할 수 있는 많은 알고리즘들이 존재한다.

 

예제 코드를 사용하여 Linear regression의 hypothesis, cost를 테스트해보았다.

 

import tensorflow as tf 

# H(x) = Wx + b

# X and Y data

x_train = [1, 2, 3]
y_train = [1, 2, 3]

W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')

# Our hypothesis XW+b

hypothesis = x_train * W + b

# cost/loss function
# reduce_mean : 평균 내주는 함수

cost = tf.reduce_mean(tf.square(hypothesis - y_train))

# Minimize
# train : 그래프의 노드

optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)
train = optimizer.minimize(cost)

# 그래프 구현 완료. 세션 만들어야 함.

# Launch the graph in a session.
# W, b를 사용하기 전에는 global_variables_initializer() 함수 사용해야 함

sess = tf.Session()
sess.run(tf.global_variables_initializer())

# Fit the line

for step in range(2001):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W), sess.run(b))

 

 

결과는 다음과 같다.

 

0 8.965018 [-0.4364577] [0.1180267]
20 0.13220851 [0.6261249] [0.5502149]
40 0.04744993 [0.73844594] [0.56603754]
60 0.042436328 [0.7597601] [0.5434045]
80 0.038535397 [0.77190953] [0.5182444]
100 0.034998376 [0.78271085] [0.4939248]
..
..
..
1900 6.0403436e-06 [0.9971455] [0.00648884]
1920 5.4859097e-06 [0.9972797] [0.00618391]
1940 4.98211e-06 [0.99740756] [0.00589328]
1960 4.525074e-06 [0.9975294] [0.00561631]
1980 4.1096655e-06 [0.9976455] [0.00535235]
2000 3.7324892e-06 [0.9977561] [0.00510082]

 

W와 b가 랜덤한 값으로 설정되었지만,

2000번의 run을 하는 동안 W=1, b=1과 매우 유사한 값으로 설정되는 것을 확인할 수 있다.

 

아래는 place holder를 사용한 코드이다.

feed_dict를 통해 값을 나중에 설정할 수 있다.

 

W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
X = tf.placeholder(tf.float32, shape=[None])
Y = tf.placeholder(tf.float32, shape=[None])

hypothesis = X * W + b
cost = tf.reduce_mean(tf.square(hypothesis - Y))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)

sess = tf.Session()
sess.run(tf.global_variables_initializer())

for step in range(2001):
    cost_val, W_val, b_val, _ = sess.run([cost, W, b, train],
                                        feed_dict = {X: [1,2,3,4,5],
                                                    Y: [2.1, 3.1, 4.1, 5.1, 6.1]})
    if step % 20 == 0 :
        print(step, cost_val, W_val, b_val)
        
print(sess.run(hypothesis, feed_dict={X:[5]}))
print(sess.run(hypothesis, feed_dict={X:[2.5]}))
print(sess.run(hypothesis, feed_dict={X:[1.5, 3.5]}))

 

결과는 다음과 같다.

 

0 26.85641 [0.30635893] [-0.6727002]
20 0.34540167 [1.3750011] [-0.2731906]
40 0.30117062 [1.3550634] [-0.1819791]
60 0.26301438 [1.331831] [-0.09801549]
80 0.22969246 [1.3100991] [-0.01955645]
...
...
...
1920 8.884772e-07 [1.0006099] [1.0977982]
1940 7.7566256e-07 [1.0005699] [1.0979425]
1960 6.775215e-07 [1.0005327] [1.0980772]
1980 5.9189017e-07 [1.0004978] [1.098203]
2000 5.1688653e-07 [1.0004653] [1.0983206]
[6.100647]
[3.599484]
[2.5990186 4.599949 ]

 

 

※ inflearn 모두를 위한 딥러닝 강좌를 듣고 정리한 내용입니다.