출처 : 모두를위한 머신러닝 (http://hunkim.github.io/ml/)
W, cost(W) 스캔 해보기¶
In [9]:
import tensorflow as tf
import matplotlib.pyplot as plt
X = [1, 2, 3]
Y = [1, 2, 3]
# W 는 계속 바뀌므로 place holder 로
W = tf.placeholder(tf.float32)
hypothesis = X * W # H(x) = Wx
cost = tf.reduce_mean(tf.square(hypothesis - Y)) # cost function
sess = tf.Session()
# place holder 가 있으므로 initialize
sess.run(tf.global_variables_initializer())
W_val = []
cost_val = []
for i in range(-30, 50):
feed_W = i * 0.1 # place holder 에 넘길 w 값 (-3~5 정도)
curr_cost, curr_w = sess.run([cost, W], feed_dict={W: feed_W})
W_val.append(curr_w)
cost_val.append(curr_cost)
fig = plt.figure(figsize=(8,6))
plt.plot(W_val, cost_val, marker='o')
plt.grid()
plt.show()
In [11]:
import tensorflow as tf
x_data = [1, 2, 3]
y_data = [1, 2, 3]
W = tf.Variable(tf.random_normal([1]), name='weight')
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
hypothesis = X * W
cost = tf.reduce_sum(tf.square(hypothesis - Y))
# Minimize
# W = 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
sess = tf.Session()
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))
- 위에서 만든 Minimze 를 해주는 내장함수
- optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
- train = optimizer.minimize(cost)
In [12]:
import tensorflow as tf
X = [1, 2, 3]
Y = [1, 2, 3]
W = tf.Variable(5.0)
hypothesis = X * W
cost = tf.reduce_mean(tf.square(hypothesis - Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
train = optimizer.minimize(cost)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(10):
print(step, sess.run(W))
sess.run(train)
'Dev > 딥러닝' 카테고리의 다른 글
04-2. Tensor Flow 에서 csv 파일 읽기 및 queue 사용법 (0) | 2018.08.17 |
---|---|
04-1. Tensor Flow 변수가 여러개일때 Linear regression (0) | 2018.08.17 |
02. Tensor Flow로 linear regression 예제 (0) | 2018.08.16 |
01. Tensor Flow 의 기본적인 operations (0) | 2018.08.16 |
Tensor Flow (gpu) 윈도우에서 설치하기 (0) | 2018.08.16 |
댓글