1. 程式人生 > >MNIST tensorflow官方卷積網路示例

MNIST tensorflow官方卷積網路示例

匯入MNIST資料

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

建立佔位符,存放輸入的mini-batch訓練集,784是影象展開的維度(28*28),10是分類的類數,是一個one-hot向量

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

定義變數weight_variable,卷積層中即卷積核,初始為均值0,標準差0.1的截斷正態分佈

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

定義變數bias_variable,即偏置, 初始為0.1的常量張量

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

定義卷積操作

關於tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None):

  • input:指需要做卷積的輸入影象,它要求是一個Tensor,具有[batch, in_height, in_width, in_channels]這樣的shape,具體含義是[訓練時一個batch的圖片數量, 圖片高度, 圖片寬度, 影象通道數],注意這是一個4維的Tensor,要求型別為float32和float64其中之一
  • filter:相當於CNN中的卷積核,它要求是一個Tensor,具有[filter_height, filter_width, in_channels, out_channels]這樣的shape,具體含義是[卷積核的高度,卷積核的寬度,影象通道數,卷積核個數],要求型別與引數input相同,第三維in_channels,就是引數input的第四維
  • strides:卷積時在影象每一維的步長,這是一個一維的向量,長度4,每跨多少步抽取資訊,[1, x_movement,y_movement, 1]
  • padding:string型別的量,只能是”SAME”,”VALID”其中之一,這個值決定了不同的卷積方式邊距處理,“SAME”表示輸出圖層和輸入圖層大小保持不變,設定為“VALID”時表示捨棄多餘邊距(丟失資訊)

結果返回一個Tensor,這個輸出,就是我們常說的feature map

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

定義最大池化操作

關於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’

返回一個Tensor,型別不變,shape仍然是[batch, height, width, channels]這種形式

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

將輸入mini-batch影象擴充套件到4維,即[batch, in_height, in_width, in_channels]的shape,以進行卷積操作

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

指定第一層卷積核的shape,即[filter_height, filter_width, in_channels, out_channels],以進行卷積操作

W_conv1 = weight_variable([5, 5, 1, 32])

指定第一層的偏置shape

b_conv1 = bias_variable([32])

使用ReLU啟用函式,由於邊距保持不變,輸出batch*28*28*32的張量

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1

池化,影象尺寸減半,輸出batch*14*14*32的張量

h_pool1 = max_pool_2x2(h_conv1)

第二層網路,最後輸出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_pool2 = max_pool_2x2(h_conv2)

第一層全連線層,加入1024個神經元的全連線層,輸出batch*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,避免過擬合

keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

第二層全連線層,softmax輸出層,輸出為batch*10的張量

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 = -tf.reduce_sum(y_ * tf.log(y_conv))

採用ADAM優化器來做梯度最速下降

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'))

啟動Session並初始化變數

sess = tf.Session()
sess.run(tf.initialize_all_variables())

開始迭代,在feed_dict中加入額外的引數keep_prob來控制dropout比例

for i in range(20000):
    batch = mnist.train.next_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, training accuracy %g' % (i, train_accuracy))
    sess.run(train_step, feed_dict = {x: batch[0], y_: batch[1], keep_prob: 0.5})

使用測試集計算準確率,視訊記憶體不夠,僅用200幅測試圖

print ('test accuracy %g' % accuracy.eval(session = sess, feed_dict={x: mnist.test.images[0:200,:], y_: mnist.test.labels[0:200,:], keep_prob: 1.0}))