1. 程式人生 > >MNIST手寫數字識別——CNN

MNIST手寫數字識別——CNN

 

參考:http://www.tensorfly.cn/tfdoc/tutorials/mnist_pros.html

網上已經有很多相關內容的部落格、資料,有很多也寫得挺好的,我也是參考別人的,這裡就不再寫原理上的東西了。附一下我做實驗的程式碼,簡單記錄一下遇到的問題。

實驗環境:spyder + python + tensorflow

程式碼:

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

mnist = input_data.read_data_sets("data/", one_hot=True, validation_size=0)  # 下載並載入mnist資料

print("mnist訓練集大小:", len(mnist.train.images))
print("mnist測試集大小:", len(mnist.test.images))
x = tf.placeholder(tf.float32, [None, 784], name="x")  # 輸入的資料佔位符
y_actual = tf.placeholder(tf.float32, shape=[None, 10], name="y_actual")  # 輸入的標籤佔位符

# 定義一個函式,用於初始化所有的權值 W
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


# 定義一個函式,用於初始化所有的偏置項 b
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


# 定義一個函式,用於構建卷積層
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


# 定義一個函式,用於構建池化層
def max_pool(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')


# 構建網路
x_image = tf.reshape(x, [-1, 28, 28, 1])  # 轉換輸入資料shape,以便於用於網路中
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(h_conv1)  # 第一個池化層

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(h_conv2)  # 第二個池化層

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])  # reshape成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  # 第一個全連線層

keep_prob = tf.placeholder("float", name="keep_prob")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  # dropout層

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_predict = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name="y_predict")  # softmax層

cross_entropy = -tf.reduce_sum(y_actual * tf.log(y_predict),name = "cross_entropy")  # 交叉熵
train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy)  # 梯度下降法
correct_prediction = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_actual, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))  # 精確度計算

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print("開始訓練:")
for i in range(3000):
    batch = mnist.train.next_batch(20)
    if i % 500 == 0: 
        train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_actual: batch[1], keep_prob:1.0})
        print('step', i, 'train_accuracy', train_accuracy)
    train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})
print("訓練結束")
 
print("開始測試:")
test_accuracy = 0.0
for i in range(100):
    batch = mnist.test.next_batch(100)
    test_accuracy_i = accuracy.eval(feed_dict={x:batch[0], y_actual:batch[1], keep_prob:1.0})
    test_accuracy += test_accuracy_i
    if (i+1) % 20 == 0:
        print('step', i+1, 'test accuracy: ', test_accuracy_i)
print("訓練集準確度: ", test_accuracy/100)    
print("測試結束")
sess.close()

實驗結果:

在訓練的時候,講batch size改為50再訓練一次。

修改訓練部分的程式碼:

print("開始訓練")
for i in range(1200):
    batch = mnist.train.next_batch(50)
    if i % 500 == 0: 
        train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_actual: batch[1], keep_prob:1.0})
        print('step', i, 'train_accuracy', train_accuracy)
    train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})
print("訓練結束")

執行結果:

  • 問題1:

執行的 時候,CPU幾乎滿負荷的在跑!!剛開始用測試集進行測試的時候,像其他部落格一樣,我把整個測試集一次性都傳進去進行測試,然後,電腦就宕機了,還一測一個死,不強制關機都不行T_T(應該是效能太差了,CPU和記憶體資源支援不了規模大一點的計算T_T)

然後我就把測試集也分成幾個小的batch去進行測試,然後結果很快就跑出來了~

感覺有必要倒騰一下,弄個GPU版的了~

  • 問題2

我本來想把訓練好的模型儲存下來,下次測試的時候只需要匯入模型就可以了。程式碼是寫了,但是實測結果發現好像不太對。這裡就先不附程式碼了,後續跟進~

  • 問題3

剛開始也覺得迷惑,為什麼這個網路經過卷積操作之後,feature map的大小竟然不減小?後來才get到,因為在卷積的時候我們選擇了引數SAME,指明瞭卷積後尺寸不變(通過填充和裁剪實現)。然後突然想起《數字影象處理》3.4.2中也提到過,看過就能大概明白了(如下圖)。所以在這個CNN模型中,feature map的size只有在池化層的時候發生變化,28*28經過第一次池化後大小為14*14,經過第二次池化後大小為7*7~

  • 問題4

感覺跑出來的正確率好像,有點......低啊,好像別人都有99%~

我發現我訓練的時候,每個訓練樣本都只用了一次~而其他的一些部落格,會將一個樣本反覆用來多訓練幾遍~

比如,這篇https://blog.csdn.net/chenhaifeng2016/article/details/62221544博文,其訓練部分程式碼和實驗結果如下:

然後我也嘗試了一下,多訓練幾次,精確度也提提升到了將近99%~

修改程式碼:

print("開始訓練:")
for i in range(10000):
    batch = mnist.train.next_batch(20)
    if i % 1000 == 0: 
        train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_actual: batch[1], keep_prob:1.0})
        print('step', i, 'train_accuracy', train_accuracy)
    train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})
print("訓練結束")

執行結果