tensorflow MNIST資料集上簡單的MLP網路
阿新 • • 發佈:2018-12-30
一、code
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data',one_hot=True) sess = tf.InteractiveSession() x = tf.placeholder("float",shape = [None,784]) y_ = tf.placeholder("float",shape = [None,10]) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x,W) + b) cross_entropy = -tf.reduce_sum(y_*tf.log(y)) sess.run(tf.initialize_all_variables()) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) #train for i in range(1000): batch = mnist.train.next_batch(50) train_step.run(feed_dict = {x:batch[0],y_:batch[1]}) res = cross_entropy.eval(feed_dict = {x:batch[0],y_:batch[1]}) #eval correct_prediction = tf.equal(tf.arg_max(y,1),tf.arg_max(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float")) print (accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
說明:
1、Tensorflow依賴於一個高效的C++後端來進行計算。與後端的這個連線叫做session。一般而言,使用TensorFlow程式的流程是先建立一個圖,然後在session中啟動它。這裡,我們使用更加方便的InteractiveSession
類。通過它,你可以更加靈活地構建你的程式碼。它能讓你在執行圖的時候,插入一些計算圖,這些計算圖是由某些操作(operations)構成的。這對於工作在互動式環境中的人們來說非常便利,比如使用IPython。如果你沒有使用InteractiveSession
,那麼你需要在啟動session之前構建整個計算圖,然後啟動該計算圖。總結:使用InteractiveSession的好處是可以動態地加入圖,如果使用session,那麼只要定義完之後,就不能繼續加入圖了 。