一、Mnist介紹
MNIST數據庫介紹:MNIST是一個手寫數字數據庫,它有60000個訓練樣本集和10000個測試樣本集。它是NIST數據庫的一個子集。MNIST數據庫官方網址爲:http://yann.lecun.com/exdb/mnist/ ,也可以在windows下直接下載,train-images-idx3-ubyte.gz、train-labels-idx1-ubyte.gz等。下載四個文件,解壓縮。解壓縮後發現這些文件並不是標準的圖像格式。這些圖像數據都保存在二進制文件中。每個樣本圖像的寬高爲28*28。
MNIST是在機器學習領域中的一個經典問題。該問題解決的是把28x28像素的灰度手寫數字圖片識別爲相應的數字,其中數字的範圍從0到9.
就像我們學習其他語言的第一個入門程序是Hello world~一樣,Mnist 就是我們深度學習入門的第一個。
話不多說,直接上代碼。
二、源碼
import tensorflow as tf
import numpy as np
#導入數據
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing
#定義佔位符
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder("float", [784])
#使用L1距離計算
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.neg(xte))), reduction_indices=1)
#得到最小距離
pred = tf.arg_min(distance, 0)
#精度計數
accuracy = 0.
#初始化所有值
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
# 在所有數據集上測試
for i in range(len(Xte)):
# 得到最近的類別
nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
# Get nearest neighbor class label and compare it to its true label
print "Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
"True Class:", np.argmax(Yte[i])
# 計算精度
if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
accuracy += 1./len(Xte)
print "Done!"
print "Accuracy:", accuracy
Done~
Accuracy:0.92
代碼運行成功~~