在上一個(gè)案例的基礎(chǔ)上,利用相似的格式,訓(xùn)練識(shí)別MINST數(shù)據(jù)集的格式。
http://www.itdecent.cn/p/73d6051bd611
其實(shí)訓(xùn)練很簡(jiǎn)單,就是用機(jī)器學(xué)習(xí)來(lái)識(shí)別手寫(xiě)數(shù)字。數(shù)據(jù)分為6w行的訓(xùn)練集和1w行的測(cè)試集。

每張圖片包含28x28個(gè)像素,所以數(shù)組是[60000,784]。 像素的強(qiáng)度在0-1之間。
根據(jù)識(shí)別概率,將每次識(shí)別的概率第一名(比如某個(gè)數(shù)字,認(rèn)為6的是0.7,認(rèn)為是8的0.3,那就取6)與真實(shí)結(jié)果對(duì)比,得到準(zhǔn)確率。

代碼如下:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#載入數(shù)據(jù)集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
#每個(gè)批次的大小.
batch_size = 10
#計(jì)算一共有多少個(gè)批次
n_batch = mnist.train.num_examples // batch_size
#定義兩個(gè)placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32)
#定義神經(jīng)網(wǎng)絡(luò)中間層
Weights_L1 = tf.Variable(tf.random_normal([784,10000]))
biases_L1 = tf.Variable(tf.zeros([10,10000]))
Wx_plus_b_L1 = tf.matmul(x,Weight_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)
#創(chuàng)建神經(jīng)網(wǎng)絡(luò)輸出層
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)
。
預(yù)測(cè)與真實(shí)標(biāo)簽比較。這里可以用兩類(lèi)函數(shù),二次代價(jià)或者交叉熵。
如果輸出神經(jīng)元是線性的,那么二次代價(jià)函數(shù)就是一種合適的選擇。如果輸出神經(jīng)元是S函數(shù),那么比較適合交叉熵代價(jià)函數(shù)。
實(shí)際運(yùn)行結(jié)果都差不多,不過(guò)交叉熵快一些。
#二次代價(jià)函數(shù)
#loss = tf.reduce_mean(tf.square(y-prediction))
#交叉熵函數(shù)
loss = tf .reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y,logits = prediciton))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
#初始化變量
init = tf.global_variables_initializer()
#結(jié)果存放在一個(gè)布爾型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一維張量中最大的值所在的位置
#求準(zhǔn)確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(5000):
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
輸出結(jié)果是0.93左右。還是沒(méi)有達(dá)到老師要求的0.95,下一篇文章?lián)QMLP或者relu激活函數(shù)(然而還不會(huì)做?。?/p>
參考文章
http://s1nh.com/post/Tensorflow-MNIST/
https://zhuanlan.zhihu.com/p/25110150