1. 程式人生 > >tensorflow編程模式的理解

tensorflow編程模式的理解

training radi predict step 節點 man ria session sof

1.MNIST數據庫下載好後,在tensorflow/examples/tutorials/mnist/下建立文件夾MNIST_data即可運行本程序
2.關鍵在與理解Operation,Tensor,Graph,只有執行session.run()時操作才真正執行

import tensorflow.examples.tutorials.mnist.input_data as input_data 
mnist = input_data.read_data_sets(‘MNIST_data/‘,one_hot = True) 
import tensorflow as tf 
# 定義計算圖
# 操作Operation為圖的節點(如下面的tf.placeholder(tf.float32,[None,784])等)
# 數據Tensor為圖的邊(如下面的x,y等)
# 添加Operation時不會立即執行,只有執行session.run(Operation或Tensor)時才會真正執行
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
W = tf.Variable(tf.zeros([784,10]),tf.float32)
b = tf.Variable(tf.zeros([10]),tf.float32)
py = tf.nn.softmax(tf.matmul(x,W) + b)
loss = -tf.reduce_mean(y*tf.log(py))

# 添加計算圖節點global_variables_initializer(),返回初始化變量的Operation
# 官方文檔解釋: Returns an Op that initializes global variables.
init = tf.global_variables_initializer();
# 獲得Session對象
sess = tf.Session()
# 真正執行初始化節點init
sess.run(init)

# 訓練MNIST數據庫
# 添加train_step計算節點,這個計算節點完成梯度下降功能,train_step為一個Operation
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
for i in range(10000):
    batch_xs,batch_ys = mnist.train.next_batch(1000) 
    # 執行梯度下降節點,tensorflow會根據計算圖反推依賴,提前計算依賴節點
    # 由於x,y中含有None,需要feed_dict = {x:batch_xs,y:batch_ys}填充數據
    sess.run(train_step,feed_dict = {x:batch_xs,y:batch_ys})
    # observe gradient descent in training set
    if i%100 == 0:
        # 計算節點correct_prediction
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(py,1))
        # 計算節點accuracy
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
        # 反推圖依賴,得到正確的accuracy
        print(‘training set accuracy: ‘,sess.run(accuracy,feed_dict={x:batch_xs,y:batch_ys}))
# 觀察測試集的performance
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(py,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(‘test set accuracy: ‘,sess.run(accuracy,feed_dict={x:batch_xs,y:batch_ys}))

tensorflow編程模式的理解