본문 바로가기
Study/Machine&Deep Learning

[ML] Linear Regression의 Hypothesis와 cost

by graygreat 2018. 5. 4.
728x90
반응형




tf.Variable : tensorflow가 자체적으로 변경시키는 variable, trainable 한 variable.


reduce_mean : 평균을 내줌

ex) t = [1, 2, 3, 4]

     tf.reduce_mean(t) ==> 2.5



linear_regression.py


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Lab 2 Linear Regression
 
import tensorflow as tf
 
# X and Y data
x_train = [123]
y_train = [123]
 
# H(x) = Wx + b
= tf.Variable(tf.random_normal([1]), name = 'weight')
= tf.Variable(tf.random_normal([1]), name = 'bias')
 
# Our hypothesis XW + b
hypothesis = x_train * W + b
 
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - y_train))
 
# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)
train = optimizer.minimize(cost)
 
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
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))
 


linear_regression_feed.py


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Lab 2 Linear Regression
import tensorflow as tf
 
= tf.Variable(tf.random_normal([1]), name = 'weight')
= tf.Variable(tf.random_normal([1]), name = 'bias')
= tf.placeholder(tf.float32, shape=[None])
= tf.placeholder(tf.float32, shape=[None])
 
# Our hypothesis XW+b
hypothesis = X * W + b
 
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
# Minimize
optimzier = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimzier.minimize(cost)
 
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
 
# Fit the line With new training data
for step in range(2001):
    cost_val, W_val, b_val, _ = sess.run([cost, W, b, train],
                                         feed_dict = {X: [12345], Y: [2.13.14.15.16.1]})
 
    if step % 20 == 0:
        print(step, cost_val, W_val, b_val)





반응형

댓글