tensorflow 시작할때 - beyondnlp/nlp GitHub Wiki
regress에서 사용하는 1차 함수를 우선 살펴보면
xW+Bb
x는 입력 데이터이고
b는 bias이다.
W는 weight 변수
x는 학습할 데이터에서 유입되고
b는 임의 값으로 초기화한후 backpropergation으로 학습하는 변수이고 column vector형식이다.
W는 임의의 값으로 초기화한후 b와 마찬가지로 backpropergation으로 학습하는 n*m matrix이다.
이를 tensorflow로 구현하면
W = tf.Variable(tf.random_uniform([784,10],-1,1), name="W")
784*10의 형태 uniform으로 값은 -1에서 1사이 값으로 초기화, 이름은 W로 붙인다.
b = tf.Variable(tf.zeros([10]), name="biases")
길이 10의 column 벡터로 0으로 초기화한다. 이름은 biases로 붙인다.
x는 ( None은 몇개인지 정해지지 않았을때 사용하는 변수명이다 )
x=tf.placeholder( tf.float32, name="x", shape=[None,784])와 같이 선언
x = None,784
W = 784, 10
b = 10
(None, 784)*(784,10)+(10) 형식이 된다.
output = tf.matmul( x, W ) + b
sess = tf.Session()
feed_dic = {"x":get_minibatch()} # get_minibatch는 1*784형식의 데이터를 가져오면 된다.
sess.run(output, feed_dict=feed_dict )
-
tensorflow의 핵심은 network graph를 만들고 placeholder를 통해 데이터를 흘러 보내면 sess.run내부에서 역전파를 통해 graph안의 weight를 계산하는 것이다.
-
placeholder에 데이터를 넣는 방법
-
변수명은 XX로 지정하면
-
feed_dict={XX: ...}형식으로 데이터를 입력받는다.
import tensorflow as tf
x_data=[1,2,3]
y_data=[1,2,3]
W=tf.Variable(tf.random_uniform([1], -1,0, 1.0 ))
b=tf.Variable(tf.random_uniform([1], -1,0, 1.0 ))
XX = tf.placeholder( tf.float32, name="X" );
YY = tf.placeholder( tf.float32, name="Y" );
h = W * XX + b;
cost = tf.reduce_mean( tf.square( h - YY ) )
optimizer = tf.train.AdamOptimizer( learning_rate = 0.1 )
train_op = optimizer.minimize( cost );
with tf.Session() as sess:
sess.run( tf.global_variables_initializer())
for step in range(100):
_, cost_val = sess.run([train_op, cost], feed_dict={ XX:x_data, YY:y_data })
print(step, cost_val, sess.run(W), sess.run(b));
print("\n====test====")
print("X:5, y:", sess.run(h, feed_dict={XX:5}))
print("X:2.5, y:", sess.run(h, feed_dict={XX:2.5}))