1. 程式人生 > >TensorFlow初學者入門(三)——MNIST進階

TensorFlow初學者入門(三)——MNIST進階

本人學習TensorFlow中的一些學習筆記和感悟,僅供學習參考,有疑問的地方可以一起交流討論,持續更新中。

本文學習地址為:TensorFlow官方文件,在此基礎上加入了自己的學習筆記和理解。

文章是建立在有一定的深度學習基礎之上的,建議有一定理論基礎之後再同步學習。

這次是利用TensorFlow搭建兩層的cnn的一個實驗,具體流程如下。

1.基本操作

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

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder('float', shape=[None, 784])
y_hat = tf.placeholder('float', shape=[None, 10])

x_image = tf.reshape(x, [-1, 28, 28, 1])

sess = tf.InteractiveSession()

mnist,x和y_hat這三個變數和上一個部落格裡的三個變數是完全相同的,就不再說明了。

x_image 是把x變成一個4d向量,其第1維的-1是預設值,第2、第3維對應圖片的寬、高,最後一維代表圖片的顏色通道數(因為是灰度圖所以這裡的通道數為1,如果是rgb彩色圖,則為3)。

InteractiveSession()和Session()的區別是:InteractiveSession()是一種交替式的會話方式,它讓自己成為了預設的會話,也就是說使用者在單一會話的情境下,不需要指明用哪個會話也不需要更改會話執行的情況下,就可以執行。詳細的解釋可以看這個部落格,對方寫的很詳細。

2.定義部分函式

2.1權重初始化

為了建立這個模型,我們需要建立大量的權重和偏置項。這個模型中的權重在初始化時應該加入少量的噪聲來打破對稱性以及避免0梯度。由於我們使用的是ReLU神經元,因此比較好的做法是用一個較小的正數來初始化偏置項,以避免神經元節點輸出恆為0的問題(dead neurons)。為了不在建立模型的時候反覆做初始化操作,我們定義兩個函式用於初始化。

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)
 

tf.truncated_normal(shape, mean, stddev):shape表示生成張量的維度,mean是均值,stddev是標準差。這個函式產生正太分佈,均值和標準差自己設定。

tf.constant(0.1,shape)用來產生大小為shape,值為0.1的張量

這兩個函式主要是用來產生每一層的初始變數W和b的。

2.2 卷積和池化

定義兩個函式conv2d和max_pool_2x2

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


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.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)卷積函式,出去name外其他5個引數分別為:

  • input: 輸入影象,要求是Tensor,具有[batch, height, width, in_channels]這樣的shape,要求型別為float32和float64。
  • filter: 卷積核,要求是Tensor,具有[height, width, in_channels, out_channels]這樣的shape,要求型別為float32和float64。注意這裡的in_channels就是input裡的in_channels。
  • strides: 卷積時在影象每一維上的步長。一維向量,長度為4。一般情況下是這種格式[1, stride, stride, 1],因為圖片的高寬對應input裡的2,3維度。
  • padding: string型別的量,只有‘SAME','VALID'兩種可選。SAME會對影象作補0操作,在卷積後圖像大小不會改變。VALID在卷積後圖像大小會變小。
  • use_cudnn_on_gpu: bool型別,是否使用cudnn加速,預設true。

返回結果仍是Tensor,shape為[batch, height, width, in_channels],就是我們說的feature map。

 

tf.nn.max_pool(value, ksize, strides, padding, name=None)。主要引數是四個,和卷積很類似:

  • value:需要池化的輸入,一般池化層接在卷積層後面,所以輸入通常是feature map,依然是[batch, height, width, channels]這樣的shape

  •  

    ksize:池化視窗的大小,取一個四維向量,一般是[1, height, width, 1],因為我們不想在batch和channels上做池化,所以這兩個維度設為了1

 

  • strides:和卷積類似,視窗在每一個維度上滑動的步長,一般也是[1, stride,stride, 1]

 

  • padding:和卷積類似,可以取'VALID' 或者'SAME'
     

定義這兩個函式純粹就是為了讓程式碼顯得更簡潔,因為每層都會呼叫卷積和池化。

3.搭建cnn網路

# 第一層卷積
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)
# 第二層卷積
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)
# 全連線層
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
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 輸出層
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# softmax
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

整個cnn的結構其實就很好理解了,結合上面的程式碼和cnn基礎知識應該不難看懂。唯一要強調的就是dropout一般用在全連線部分,卷積和輸出不會使用dropout,程式碼裡的keep_prob是要保留的節點比例,一般訓練的時候設為0.5,測試的時候設為1.0。y_conv是整個cnn的輸出。

4.訓練和評估模型

# 訓練評估模型
cross_entropy = -tf.reduce_sum(y_hat*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_hat, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
sess.run(tf.initialize_all_variables())
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_hat: batch[1], keep_prob: 1.0})
        print("step %d, training accuracy %g" % (i, train_accuracy))
    train_step.run(feed_dict={x: batch[0], y_hat: batch[1], keep_prob: 0.5})

print("test accuracy %g" % accuracy.eval(feed_dict={
    x: mnist.test.images, y_hat: mnist.test.labels, keep_prob: 1.0
}))

和上一篇部落格裡對迴歸模型的訓練和評估基本上是一樣的,沒有特別的東西要講的,就是說一下如果沒有GPU或者只是想試一下整體效果的,不建議將迴圈次數設那麼大。最後模型的準確率能達到99.2%。

5.完整程式碼

完整程式碼如下,歡迎交流討論

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


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)


def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


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


mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
sess = tf.InteractiveSession()

x = tf.placeholder('float', shape=[None, 784])
y_hat = tf.placeholder('float', shape=[None, 10])
x_image = tf.reshape(x, [-1, 28, 28, 1])
# 第一層卷積
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)
# 第二層卷積
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)
# 全連線層
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
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 輸出層
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# softmax
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 訓練評估模型
cross_entropy = -tf.reduce_sum(y_hat*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_hat, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
sess.run(tf.initialize_all_variables())
for i in range(200):
    batch = mnist.train.next_batch(50)
    if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_hat: batch[1], keep_prob: 1.0})
        print("step %d, training accuracy %g" % (i, train_accuracy))
    train_step.run(feed_dict={x: batch[0], y_hat: batch[1], keep_prob: 0.5})

print("test accuracy %g" % accuracy.eval(feed_dict={
    x: mnist.test.images, y_hat: mnist.test.labels, keep_prob: 1.0
}))