1. 程式人生 > >TensorFlow+MNIST例項講解

TensorFlow+MNIST例項講解

本人使用的環境是:TensorFlow1.1.0+python3.6+GPU

MNIST資料集:10類,訓練庫有60,000張手寫數字影象,測試庫有10,000張。黑白,28*28

模型:CNN,卷積神經網路對影象特徵的提取和抽象能力尤為顯著

首先匯入MNIST資料集

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
sess = tf.InteractiveSession()
建立權重函式,標準差設為0.1
def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)
建立偏置函式
def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)
建立二維卷積函式,引數x為輸入,W為卷積的引數,strides為卷積模板移動的步長,padding為邊界的處理方式
def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
最大池化函式 2*2,最大池化會保留原始畫素塊中灰度值最高的那一個畫素,即保留最顯著的特徵
def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')  
定義輸入的placeholder,x為特徵,將1D的輸入向量轉為2D的圖片結構(28*28=784),y_為真實的label,tf.reshape為tensor變形函式,由於只有一個顏色通道,則最終尺寸為[-1,28,28,1],-1為樣本數量不固定,1為顏色通道數量
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
x_image = tf.reshape(x, [-1,28,28,1])
定義第一個卷積層,卷積核尺寸為5*5,1個顏色通道,32個不同的卷積核
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
定義第二個卷積層,卷積核的數量為64,即說明這一層的卷積會提取64種特徵
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
定義全連線層,前面通過兩次步長為2*2的最大池化,則圖片尺寸有28*28變成了7*7;而第二個卷積層的卷積核數量為64,其輸出的tensor尺寸為7*7*64;tf.reshape函式對第二個卷積層的輸出tensor進行變形,將其轉成1D的向量,然後連線一個全連線層,隱含節點為1024,並使用ReLU
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
Dropout層,通過一個placeholder傳入keep_prob比率來控制;在訓練時,隨機丟棄一部分節點的資料來減輕過擬合,預測時則保留全部資料來追求最好的預測效能
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
Softmax層,得到最後的概率輸出

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

定義損失函式cross_entropy,優化器Adam,並給予一個比較小的學習速率le-4

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
定義評測準確率的操作
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
開始訓練過程:首先初始化引數,設定訓練時Dropout的keep_prob比率為0.5;然後使用大小為50的mini-match,共進行20000次訓練迭代,參與訓練的樣本數量總共為100萬,其中每100次訓練,對準確率進行一次評測
tf.global_variables_initializer().run()
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print("step %d, training accuracy %g"%(i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
訓練完成後,在最終的測試集上進行全面的測試,得到整體的分類準確率
print("test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

最後,CNN模型得到的準確率為99.19%。依靠卷積核的權值共享,CNN的引數量沒有爆炸,降低計算量的同時也減輕了過擬合,因此整個模型的效能有較大的提升。

本人測試的結果如下: