반응형
※본 포스팅은 직접 강의하는 내용이 아닌, 김성훈 교수님의 머신러닝 강의를 정리하기 위한 포스팅입니다.
김성훈 교수님의 강의는 모두를 위한 머신러닝/딥러닝(http://hunkim.github.io/ml)에서 들을 수 있습니다.
1.Building graph using TF operation
# Lab 2 Linear Regression
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
# 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
W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# Now we can use X and Y in place of x_data and y_data
# # placeholders for a tensor that will be always fed using feed_dict
# See http://stackoverflow.com/questions/36693740/
X = tf.placeholder(tf.float32, shape=[None])
Y = 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
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
참고) tf.Variable(임의의 데이터)
- 변수를 의미
- 임의의 값을 지정
- 그래프를 계산하면서 최적화 할 변수들 입력 시 사용
참고) tf.placeholder(데이터 구조, 타입)
- 값을 입력 받을 수 있는 그래프
- feed_dict라는 인수를 사용해 딕셔너리 형태로 입력 값을 받음
- key는 placeholder의 변수명이 되며, value는 넣고 싶은 데이터를 넣음
- None은 크기가 정해지지 않았음을 의미
참고) tf.reduce_mean
- tf.reduce* 함수는 다양한 연산을 통해 차원을 줄이는 함수
- 그 중 reduce_mean은 배열의 평균을 구하는 함수
- int로 함수를 넣을 경우 값이 int값으로 나오기 때문에 올바른 평균 값을 얻지 못할 수 있음
참고) tf.train.GradientDescentOptimizer / minimize
- Gradient Descent(경사 하강법) 최적화 함수
- 최종 목표는 비용의 최소화이므로, 최적화 함수의 최소값을 호출
2.3.Run/update graph and get results
# 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):
cost_val, W_val, b_val, _ = \
sess.run([cost, W, b, train],
feed_dict={X: [1, 2, 3], Y: [1, 2, 3]})
if step % 20 == 0:
print(step, cost_val, W_val, b_val)
# Learns best fit W:[ 1.], b:[ 0]
반응형
'IT 기록 > 머신러닝' 카테고리의 다른 글
[머신러닝]03-2.Linear Regression의 cost 최소화 Tensorflow 구현 (0) | 2018.07.11 |
---|---|
[머신러닝]03-1.Linear Regression의 cost 최소화 알고리즘 (0) | 2018.07.09 |
[머신러닝]02-1.Linear Regression의 개념 (0) | 2018.07.02 |
[머신러닝]01-2.Tensorflow의 기본 (0) | 2018.06.25 |
[머신러닝]01-1.머신러닝의 개념과 용어 (0) | 2018.06.24 |
댓글