본문 바로가기

잡다한 IT/머신러닝 & 딥러닝

03-2 Minimizing Cost without tensorflow APIs

■ 텐서플로우 함수를 사용하지 않고 Cost Minimizing 기능을 구현한다.


▶ 내장함수를 사용하지 않고 편미분으로 직접 구현함

learning_rate = 0.1

- 학습률을 설정한다


gradient = tf.reduce_mean((W*X-Y)*X)

- Cost 함수를 W에 대한 편미분을 했을 때의 값

- 편미분을 통하여 기울기 값을 구한다.


descent = W - learning_rate*gradient

- 현재의 W값에서 학습율과 기울기의 곱을 한 값을 뺀다.


update = W.assign(descent)

- 그 값을 W에 업데이트 한다.



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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Lab 3-2 Minimizing Cost
 
import tensorflow as tf
 
tf.set_random_seed(777)  # for reproducibility
 
 
x_data = [123]
 
y_data = [123]
 
 
# Try to find values for W and b to compute y_data = W * x_data + b
 
# We know that W should be 1 and b should be 0
 
# But let's use TensorFlow to figure it out
 
= tf.Variable(tf.random_normal([1]), name='weight')
 
 
= tf.placeholder(tf.float32)
 
= tf.placeholder(tf.float32)
 
 
# Our hypothesis for linear model X * W
 
hypothesis = X * W
 
 
# cost/loss function
 
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
 
# Minimize: Gradient Descent using derivative: W -= learning_rate * derivative
 
learning_rate = 0.1
 
gradient = tf.reduce_mean((W * X - Y) * X)
 
descent = W - learning_rate * gradient
 
update = W.assign(descent)
 
 
# Launch the graph in a session.
 
sess = tf.Session()
 
# Initializes global variables in the graph.
 
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))
 
cs


반응형