출처 : 모두를위한 머신러닝 (http://hunkim.github.io/ml/)
이론
예제
Hypothesis and cost function¶
학슴을 통해 cost function 을 최소화 하는 W, b 를 찾아야 함.
In [1]:
import tensorflow as tf
x_train = [1, 2, 3]
y_train = [1, 2, 3]
# Variable : Tensorflow 가 사용하는 변수
# Training 과정중에서 변함
W = tf.Variable(tf.random_normal([1]), name='weight') # rank 가 1인 random 값
b = tf.Variable(tf.random_normal([1]), name='bias')
hypothesis = x_train * W + b # hypothesis node
# Tensorflow 내장 수학함수로 표현함
# reduce_mean = 평균내주는 함수
cost = tf.reduce_mean(tf.square(hypothesis - y_train))
# Minimize cost
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
Run/update graph and get results¶
In [4]:
sess = tf.Session()
# tf.Variable 을 사용할경우 변수 initial lize 를 시켜야함
sess.run(tf.global_variables_initializer())
for step in range(2001):
sess.run(train)
# train 이 매 스탭 run 할때마다 cost, W, b 값들이 바뀜
if step % 100 == 0: # 100step 마다 값 관찰
print(step, sess.run(cost), sess.run(W), sess.run(b))
Using placeholders¶
In [3]:
import tensorflow as tf
X = tf.placeholder(tf.float32, shape=[None])
Y = tf.placeholder(tf.float32, shape=[None])
W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
hypothesis = X * W + b
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize cost
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
sess = tf.Session()
# tf.Variable 을 사용할경우 변수 initial lize 를 시켜야함
sess.run(tf.global_variables_initializer())
for step in range(2001):
# run 결과를 변수로 받음
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 % 200 == 0:
print(step, cost_val, W_val, b_val)
Training 으로 얻어진 Hypothesis test¶
In [4]:
print(sess.run(hypothesis, feed_dict={X: [13]}))
print(sess.run(hypothesis, feed_dict={X: [2.5, 7.2]}))
'Dev > 딥러닝' 카테고리의 다른 글
04-2. Tensor Flow 에서 csv 파일 읽기 및 queue 사용법 (0) | 2018.08.17 |
---|---|
04-1. Tensor Flow 변수가 여러개일때 Linear regression (0) | 2018.08.17 |
03. TensorFlow Linear Regression 의 cost 최소화 구현 (0) | 2018.08.17 |
01. Tensor Flow 의 기본적인 operations (0) | 2018.08.16 |
Tensor Flow (gpu) 윈도우에서 설치하기 (0) | 2018.08.16 |
댓글