Tensorflow實踐:CNN實現MNIST手寫識別模型


轉載請注明出處:http://www.cnblogs.com/willnote/p/6874699.html

前言

本文假設大家對CNN、softmax原理已經比較熟悉,着重點在於使用Tensorflow對CNN的簡單實踐上。所以不會對算法進行詳細介紹,主要針對代碼中所使用的一些函數定義與用法進行解釋,並給出最終運行代碼。如果對Tensorflow的一些基本操作不熟悉的話,推薦先看下極客學院的這篇文章再回來看本文。

數據集

數據集是MNIST,一個入門級的計算機視覺數據集,它包含各種手寫數字圖片:
MNIST數據示例
每張圖片包含28X28個像素點,標簽即為圖片中的數字。

問題

使用MNIST數據集進行訓練,識別圖片中的手寫數字(0到9共10類)。

思路

使用一個簡單的CNN網絡結構如下,括號里邊表示tensor經過本層后的輸出shape:

  • 輸入層(28 * 28 * 1)
  • 卷積層1(28 * 28 * 32)
  • pooling層1(14 * 14 * 32)
  • 卷積層2(14 * 14 * 64)
  • pooling層2(7 * 7 * 64)
  • 全連接層(1 * 1024)
  • softmax層(10)

具體的參數看后邊的代碼注釋。

函數說明

在擼代碼前,先對幾個會用到的主要函數中的主要參數進行說明。

tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

隨機產生一個形狀為shape的服從截斷正態分布(均值為mean,標准差為stddev)的tensor。截斷的方法根據官方API的定義為,如果單次隨機生成的值偏離均值2倍標准差之外,就丟棄並重新隨機生成一個新的數。

tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)

  • input
    input是一個形狀為[batch, in_height, in_width, in_channels]的tensor:
    • batch
      每次batch數據的數量。
      • in_height,in_width
        輸入矩陣的高和寬,如輸入層的圖片是28*28,則in_height和in_width就都為28。
    • in_channels
      輸入通道數量。如輸入層的圖片經過了二值化,則通道為1,如果輸入層的圖片是RGB彩色的,則通道為3;再如卷積層1有32個通道,則pooling層1的輸入(卷積層1的輸出)即為32通道。
  • filter
    filter是一個形狀為[filter_height, filter_width, in_channels, out_channels]的tensor:
    • filter_height, filter_width
      卷積核的高與寬。如卷積層1中的卷積核,filter_height, filter_width都為28。
    • in_channels
      輸入通道數量。
    • out_channels
      輸出通道的數量。如輸入數據經過卷積層1后,通道數量從1變為32。
  • strides
    strides是指滑動窗口(卷積核)的滑動規則,包含4個維度,分別對應input的4個維度,即每次在input tensor上滑動時的步長。其中batch和in_channels維度一般都設置為1,所以形狀為[1, stride, stride, 1]
  • padding
    這個在之前的文章中說過,這里不再復述,看這里回顧。

tf.nn.max_pool(value, ksize, strides, padding, data_format='NHWC', name=None)

  • value
    以tf.nn.conv2d()函數的參數input理解即可。
  • ksize
    滑動窗口(pool)的大小尺寸,這里注意這個大小尺寸並不僅僅指2維上的高和寬,ksize的每個維度同樣對應input的各個維度(只是大小,不是滑動步長),同樣的,batch和in_channels維度多設置為1。如pooling層1的ksize即為[1, 2, 2, 1],即用一個2*2的窗口做pooling。
  • strides
    同tf.nn.conv2d()函數的參數strides。
  • padding
    這里

tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None)

這里不對dropout的算法進行描述,如果不知道自行百度。

  • x
    輸入tensor。
  • keep_prob
    x中每個元素的輸出概率,輸出為原值或0。

代碼

talk is cheap, show me the code.

#coding:utf-8
import tensorflow as tf
import MNIST_data.input_data as input_data
import time

"""
權重初始化
初始化為一個接近0的很小的正數
"""
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)

"""
卷積和池化,使用卷積步長為1(stride size),0邊距(padding size)
池化用簡單傳統的2x2大小的模板做max pooling
"""
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding = 'SAME')
    # tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)
    # x(input)  : [batch, in_height, in_width, in_channels]
    # W(filter) : [filter_height, filter_width, in_channels, out_channels]
    # strides   : The stride of the sliding window for each dimension of input.
    #             For the most common case of the same horizontal and vertices strides, strides = [1, stride, stride, 1]

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize = [1, 2, 2, 1],
                          strides = [1, 2, 2, 1], padding = 'SAME')
    # tf.nn.max_pool(value, ksize, strides, padding, data_format='NHWC', name=None)
    # x(value)              : [batch, height, width, channels]
    # ksize(pool大小)        : A list of ints that has length >= 4. The size of the window for each dimension of the input tensor.
    # strides(pool滑動大小)   : A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor.

start = time.clock() #計算開始時間
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #MNIST數據輸入

"""
第一層 卷積層

x_image(batch, 28, 28, 1) -> h_pool1(batch, 14, 14, 32)
"""
x = tf.placeholder(tf.float32,[None, 784])
x_image = tf.reshape(x, [-1, 28, 28, 1]) #最后一維代表通道數目,如果是rgb則為3 
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)
# x_image -> [batch, in_height, in_width, in_channels]
#            [batch, 28, 28, 1]
# W_conv1 -> [filter_height, filter_width, in_channels, out_channels]
#            [5, 5, 1, 32]
# output  -> [batch, out_height, out_width, out_channels]
#            [batch, 28, 28, 32]
h_pool1 = max_pool_2x2(h_conv1)
# h_conv1 -> [batch, in_height, in_weight, in_channels]
#            [batch, 28, 28, 32]
# output  -> [batch, out_height, out_weight, out_channels]
#            [batch, 14, 14, 32]

"""
第二層 卷積層

h_pool1(batch, 14, 14, 32) -> h_pool2(batch, 7, 7, 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_pool1 -> [batch, 14, 14, 32]
# W_conv2 -> [5, 5, 32, 64]
# output  -> [batch, 14, 14, 64]
h_pool2 = max_pool_2x2(h_conv2)
# h_conv2 -> [batch, 14, 14, 64]
# output  -> [batch, 7, 7, 64]

"""
第三層 全連接層

h_pool2(batch, 7, 7, 64) -> h_fc1(1, 1024)
"""
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

h_fc1 -> h_fc1_drop, 訓練中啟用,測試中關閉
"""
keep_prob = tf.placeholder("float")
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)

"""
訓練和評估模型

ADAM優化器來做梯度最速下降,feed_dict中加入參數keep_prob控制dropout比例
"""
y_ = tf.placeholder("float", [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv)) #計算交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #使用adam優化器來以0.0001的學習率來進行微調
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) #判斷預測標簽和實際標簽是否匹配
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))

sess = tf.Session() #啟動創建的模型
sess.run(tf.initialize_all_variables()) #舊版本
#sess.run(tf.global_variables_initializer()) #初始化變量

for i in range(5000): #開始訓練模型,循環訓練5000次
    batch = mnist.train.next_batch(50) #batch大小設置為50
    if i % 100 == 0:
        train_accuracy = accuracy.eval(session = sess,
                                       feed_dict = {x:batch[0], y_:batch[1], keep_prob:1.0})
        print("step %d, train_accuracy %g" %(i, train_accuracy))
    train_step.run(session = sess, feed_dict = {x:batch[0], y_:batch[1],
                   keep_prob:0.5}) #神經元輸出保持不變的概率 keep_prob 為0.5

print("test accuracy %g" %accuracy.eval(session = sess,
      feed_dict = {x:mnist.test.images, y_:mnist.test.labels,
                   keep_prob:1.0})) #神經元輸出保持不變的概率 keep_prob 為 1,即不變,一直保持輸出

end = time.clock() #計算程序結束時間
print("running time is %g s") % (end-start)

參考

  1. 深入MNIST
  2. 學習TensorFlow的第三天
  3. tensorflow官方API - tf.truncated_normal
  4. tensorflow官方API - tf.nn.conv2d
  5. tensorflow官方API - tf.nn.max_pool
  6. tensorflow官方API - tf.nn.dropout


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM