一、概述及完整代碼
對MNIST(MixedNational Institute of Standard and Technology database)這個非常簡單的機(jī)器視覺數(shù)據(jù)集,Tensorflow為我們進(jìn)行了方便的封裝,可以直接加載MNIST數(shù)據(jù)成我們期望的格式.本程序使用Softmax Regression訓(xùn)練手寫數(shù)字識別的分類模型.
先看完整代碼:
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data", one_hot=True) print(mnist.train.images.shape, mnist.train.labels.shape) print(mnist.test.images.shape, mnist.test.labels.shape) print(mnist.validation.images.shape, mnist.validation.labels.shape) #構(gòu)建計算圖 x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) #在會話sess中啟動圖 sess = tf.InteractiveSession() #創(chuàng)建InteractiveSession對象 tf.global_variables_initializer().run() #全局參數(shù)初始化器 for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) train_step.run({x: batch_xs, y_: batch_ys}) #測試驗證階段 #沿著第1條軸方向取y和y_的最大值的索引并判斷是否相等 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) #轉(zhuǎn)換bool型tensor為float32型tensor并求平均即得到正確率 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels})) 二、詳細(xì)解讀
首先看一下使用TensorFlow進(jìn)行算法設(shè)計訓(xùn)練的核心步驟
1.定義算法公式,也就是神經(jīng)網(wǎng)絡(luò)forward時的計算;
2.定義loss,選定優(yōu)化器,并制定優(yōu)化器優(yōu)化loss;
3.在訓(xùn)練集上迭代訓(xùn)練算法模型;
4.在測試集或驗證集上對訓(xùn)練得到的模型進(jìn)行準(zhǔn)確率評測.
首先創(chuàng)建一個Placeholder,即輸入張量數(shù)據(jù)的地方,第一個參數(shù)是數(shù)據(jù)類型dtype,第二個參數(shù)是tensor的形狀shape.接下來創(chuàng)建SoftmaxRegression模型中的weights(W)和biases(b)的Variable對象,不同于存儲數(shù)據(jù)的tensor一旦使用掉就會消失,Variable在模型訓(xùn)練迭代中是持久存在的,并且在每輪迭代中被更新Variable初始化可以是常量或隨機(jī)值.接下來實現(xiàn)模型算法y = softmax(Wx + b),TensorFlow語言只需要一行代碼,tf.nn包含了大量神經(jīng)網(wǎng)絡(luò)的組件,頭tf.matmul是矩陣乘法函數(shù).TensorFlow將模型中的forward和backward的內(nèi)容都自動實現(xiàn),只要定義好loss,訓(xùn)練的時候會自動求導(dǎo)并進(jìn)行梯度下降,完成對模型參數(shù)的自動學(xué)習(xí).定義損失函數(shù)lossfunction來描述分類精度,對于多分類問題通常使用cross-entropy交叉熵.先定義一個placeholder輸入真實的label,tf.reduce_sum和tf.reduce_mean的功能分別是求和和求平均.構(gòu)造完損失函數(shù)cross-entropy后,再定義一個優(yōu)化算法即可開始訓(xùn)練.我們采用隨機(jī)梯度下降SGD,定義好后TensorFlow會自動添加許多運(yùn)算操作來實現(xiàn)反向傳播和梯度下降,而給我們提供的是一個封裝好的優(yōu)化器,只需要每輪迭代時feed數(shù)據(jù)給它就好.設(shè)置好學(xué)習(xí)率.
新聞熱點
疑難解答
圖片精選