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:mnist.test.images,y:mnist.test.labels}))