TensorFlow入門(三)多層 CNNs 實現 mnist分類

歡迎轉載,但請務必註明原文出處及作者信息。

深入MNIST

refer: http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_pros.html
@author: huangyongye
@date: 2017-02-24

之前在keras中用同樣的網絡和同樣的數據集來做這個例子的時候。keras佔用了 5647M 的顯存(訓練過程中設了 validation_split = 0.2, 也就是1.2萬張圖)。

但是我用 tensorflow 自己寫的 batch=50 來測試發現呀只有529的佔用顯存!!!只是在最後做測試的時候因爲是對10000多張圖片一次性做預測才佔用了 8721M 的顯存這裏的測試集是 1 萬張。如果把預測時候的 batch 也設得比較小的話,那麼整個網絡只需要很小的顯存了。

import numpy as np
import tensorflow as tf

# 設置按需使用GPU
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.InteractiveSession(config=config)

1.導入數據,用 tensorflow 導入

# 用tensorflow 導入數據
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
# 看看咱們樣本的數量
print mnist.test.labels.shape
print mnist.train.labels.shape
(10000, 10)
(55000, 10)

或者從keras中導入數據

# 注意: keras 中導入數據形式不一樣哦,需要根據具體情況調整
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print 'X_train.shape=', X_train.shape
print 'y_train.shape=', y_train.shape

# TensorFlow 類別需要使用 one-hot 類型
from keras.utils import np_utils
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
print X_train.shape
print y_train.shape
X_train.shape= (60000, 28, 28)
y_train.shape= (60000,)
(60000, 28, 28)
(60000, 10)

2. 構建網絡

# 權值初始化
def weight_variable(shape):
    # 用正態分佈來初始化權值
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    # 本例中用relu激活函數,所以用一個很小的正偏置較好
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

# 定義卷積層
def conv2d(x, W):
    # 默認 strides[0]=strides[3]=1, strides[1]爲x方向步長,strides[2]爲y方向步長
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')

# pooling 層
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')


X_ = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])

# 把X轉爲卷積所需要的形式
X = tf.reshape(X_, [-1, 28, 28, 1])
# 第一層卷積:5×5×1卷積核32個 [5,5,1,32],h_conv1.shape=[-1, 28, 28, 32]
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(X, W_conv1) + b_conv1)

# 第一個pooling 層[-1, 28, 28, 32]->[-1, 14, 14, 32]
h_pool1 = max_pool_2x2(h_conv1)

# 第二層卷積:5×5×32卷積核64個 [5,5,32,64],h_conv2.shape=[-1, 14, 14, 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)

# 第二個pooling 層,[-1, 14, 14, 64]->[-1, 7, 7, 64] 
h_pool2 = max_pool_2x2(h_conv2)

# flatten層,[-1, 7, 7, 64]->[-1, 7*7*64],即每個樣本得到一個7*7*64維的樣本
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])

# fc1
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# dropout: 輸出的維度和h_fc1一樣,只是隨機部分值被值爲零
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# 輸出層
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)

3.訓練和評估

在測試的時候不使用 mini_batch, 那麼測試的時候會佔用較多的GPU(4497M),這在 notebook 交互式編程中是不推薦的。

cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
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, "float"))
sess.run(tf.initialize_all_variables())
for i in range(10000):
    batch = mnist.train.next_batch(50)
    if i%1000 == 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})
WARNING:tensorflow:From <ipython-input-5-94e05db0c125>:5: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
step 0, training accuracy 0.12
step 1000, training accuracy 0.92
step 2000, training accuracy 0.98
step 3000, training accuracy 0.96
step 4000, training accuracy 1
step 5000, training accuracy 1
step 6000, training accuracy 1
step 7000, training accuracy 1
step 8000, training accuracy 1
step 9000, training accuracy 1
test accuracy 0.9921

下面改成了 test 也用 mini_batch 的形式, 顯存只用了 529M,所以還是很成功的。

# 題外話:在做這個例子的過程中遇到過:資源耗盡的錯誤,爲什麼?
# -> 因爲之前每次做 train_acc  的時候用了全部的 55000 張圖,顯存爆了.

# 1.損失函數:cross_entropy
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
# 2.優化函數:AdamOptimizer
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 3.預測準確結果統計
# 預測值中最大值(1)即分類結果,是否等於原始標籤中的(1)的位置。argmax()取最大值所在的下標
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.arg_max(y_, 1))  
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


# 如果一次性來做測試的話,可能佔用的顯存會比較多,所以測試的時候也可以設置較小的batch來看準確率
test_acc_sum = tf.Variable(0.0)
batch_acc = tf.placeholder(tf.float32)
new_test_acc_sum = tf.add(test_acc_sum, batch_acc)
update = tf.assign(test_acc_sum, new_test_acc_sum)

# 定義了變量必須要初始化,或者下面形式
sess.run(tf.global_variables_initializer())
# 或者某個變量單獨初始化 如:
# x.initializer.run()

# 訓練
for i in range(5000):
    X_batch, y_batch = mnist.train.next_batch(batch_size=50)
    if i % 500 == 0:
        train_accuracy = accuracy.eval(feed_dict={X_: X_batch, y_: y_batch, keep_prob: 1.0})
        print "step %d, training acc %g" % (i, train_accuracy)
    train_step.run(feed_dict={X_: X_batch, y_: y_batch, keep_prob: 0.5})  

# 全部訓練完了再做測試,batch_size=100
for i in range(100): 
    X_batch, y_batch = mnist.test.next_batch(batch_size=100)
    test_acc = accuracy.eval(feed_dict={X_: X_batch, y_: y_batch, keep_prob: 1.0})
    update.eval(feed_dict={batch_acc: test_acc})
    if (i+1) % 20 == 0:
        print "testing step %d, test_acc_sum %g" % (i+1, test_acc_sum.eval())
print " test_accuracy %g" % (test_acc_sum.eval() / 100.0)
step 0, training acc 0.16
step 500, training acc 0.9
step 1000, training acc 0.98
step 1500, training acc 0.96
step 2000, training acc 1
step 2500, training acc 0.98
step 3000, training acc 1
step 3500, training acc 0.96
step 4000, training acc 1
step 4500, training acc 1
testing step 20, test_acc_sum 19.65
testing step 40, test_acc_sum 39.21
testing step 60, test_acc_sum 58.86
testing step 80, test_acc_sum 78.71
testing step 100, test_acc_sum 98.54
 test_accuracy 0.9854

4. 查看網絡中間結果

在學習 CNN 的過程中,老是看到他們用圖片的形式展示了中間層卷積的輸出。好吧,這下我必須得自己實現以下看看呀!!!

關於 python 圖片操作主要有 matplotlib 和 PIL 兩個庫(refer to: http://www.cnblogs.com/yinxiangnan-charles/p/5928689.html)。

我們使用 matplotlib 來完成這個任務。

4.1 圖像操作基礎

# 我們先來看看數據是什麼樣的
img1 = mnist.train.images[1]
label1 = mnist.train.labels[1]
print label1  # 所以這個是數字 6 的圖片
print 'img_data shape =', img1.shape  # 我們需要把它轉爲 28 * 28 的矩陣
img1.shape = [28, 28]
[ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
img_data shape = (784,)
import matplotlib.pyplot as plt
# import matplotlib.image as mpimg  # 用於讀取圖片,這裏用不上

print img1.shape
(28, 28)
plt.imshow(img1)
plt.axis('off') # 不顯示座標軸
plt.show()   

這裏寫圖片描述

plt.imshow?

好吧,是顯示了圖片,但是結果是熱度圖像。我們想顯示的是灰度圖像。

# 我們可以通過設置 cmap 參數來顯示灰度圖
plt.imshow(img1, cmap='gray') # 'hot' 是熱度圖
plt.show()

這裏寫圖片描述

我們想看 Conv1 層的32個卷積濾波後的結果,顯示在同一張圖上。 python 中也有 plt.subplot(121) 這樣的方法來幫我們解決這個問題。如下:先看兩個試試

plt.subplot?
img1.shape
(1, 784)
plt.subplot(4,8,1)
plt.imshow(img1, cmap='gray')
plt.axis('off')
plt.subplot(4,8,2)
plt.imshow(img1, cmap='gray')
plt.axis('off')
plt.show()

這裏寫圖片描述

4.2 顯示網絡中間結果

好了,有了前面的圖像操作基礎,我們就該試試吧!!!

# 首先應該把 img1 轉爲正確的shape (None, 784)
X_img = img1.reshape([-1, 784])
y_img = mnist.train.labels[1].reshape([-1, 10])
# 我們要看 Conv1 的結果,即 h_conv1
result = h_conv1.eval(feed_dict={X_: X_img, y_: y_img, keep_prob: 1.0})
print result.shape
print type(result)
(1, 28, 28, 32)
<type 'numpy.ndarray'>

好的,我們成功的計算得到了 h_conv1,那麼趕緊 imshow() 看看吧!!!

for _ in xrange(32):
    show_img = result[:,:,:,_]
    show_img.shape = [28, 28]
    plt.subplot(4, 8, _ + 1)
    plt.imshow(show_img, cmap='gray')
    plt.axis('off')
plt.show()

這裏寫圖片描述

哈哈,成功啦!從上面的結果中,我們可以看到不同的濾波器(卷積核)學習到了不同的特徵。比如第一行中,第一個濾波器學習到了邊緣信息,第5個卷積核,則學習到了骨幹的信息。感覺好有趣,不由自主的想對另一個數字看看。

# 輸出前10個看看,我選擇數字 9 來試試
print mnist.train.labels[:10]
[[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]
 [ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]]
# 首先應該把 img1 轉爲正確的shape (None, 784)
X_img = mnist.train.images[2].reshape([-1, 784])
y_img = mnist.train.labels[1].reshape([-1, 10]) # 這個標籤只要維度一致就行了
result = h_conv1.eval(feed_dict={X_: X_img, y_: y_img, keep_prob: 1.0})

for _ in xrange(32):
    show_img = result[:,:,:,_]
    show_img.shape = [28, 28]
    plt.subplot(4, 8, _ + 1)
    plt.imshow(show_img, cmap='gray')
    plt.axis('off')
plt.show()

這裏寫圖片描述

第一個核還是主要學習到了邊緣特徵,第五個核還是學到了骨幹特徵(當然在某種程度上)。好吧,本次就到這啦!

本文代碼:https://github.com/yongyehuang/Tensorflow-Tutorial

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章