練習(xí):使用 CNN(卷積神經(jīng)網(wǎng)絡(luò))識別 MNIST手寫字體— Tensorflow
本文利用卷積神經(jīng)網(wǎng)絡(luò)將 MNIST 數(shù)據(jù)集的28×28像素的灰度手寫數(shù)字圖片識別為相應(yīng)的數(shù)字。
mnist有六萬多張手寫數(shù)字的圖片,每個圖片用28x28的像素矩陣表示。所以我們的輸入層每個案列的特征個數(shù)就有28x28=784個;因為數(shù)字有0,1,2…9共十個,所以我們的輸出層是個1x10的向量。輸出層是十個小于1的非負(fù)數(shù),表示該預(yù)測是0,1,2…9的概率,我們選取最大概率所對應(yīng)的數(shù)字作為我們的最終預(yù)測。
-
首先導(dǎo)入庫
import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.cm as cm tf.logging.set_verbosity(tf.logging.ERROR) # 由于版本問題,可以忽略 tensor 的警告 -
然后導(dǎo)入數(shù)據(jù)集,并對參數(shù)進行設(shè)置
# 設(shè)置 Learning_rate = 1e-4 # 學(xué)習(xí)率 Training_iterations = 2500 # 迭代次數(shù) Dropout = 0.5 # 每次殺死50%的神經(jīng)元,防止過擬合 Batch_size = 50 # 每次迭代50張圖像 Validation_size = 2000 # 驗證集 Image_to_display = 10 # 輸出10種類型 # 讀取訓(xùn)練集 data = pd.read_csv('mnist_train.csv') print('data({0[0]}, {0[1]})'.format(data.shape)) print(data.head())
-
對數(shù)據(jù)進行處理,得到圖像的像素、寬度和高度
# 數(shù)據(jù)簡單預(yù)處理 images = data.iloc[:,1:].values images = images.astype(np.float) images = np.multiply(images, 1.0 / 255.0) # 歸一化數(shù)據(jù) print('images({0[0]}, {0[1]})'.format(images.shape)) # 圖像像素 image_size = images.shape[1] print('image_size => {0}'.format(image_size)) # 圖像的寬和高 image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8) print('image_width => {0}\nimage_height => {1}'.format(image_width, image_height))

-
查看當(dāng)前圖片
def display(img): one_image = img.reshape(image_width, image_height) # 轉(zhuǎn)換圖像格式 plt.axis('off') plt.imshow(one_image, cmap=cm.binary) plt.show() display(images[Image_to_display])

從圖中可以看出,有可能數(shù)字5,或者數(shù)字6
-
查看實際對應(yīng)的數(shù)字
# 查看 label labels_flat = data.iloc[:,0].values.ravel() print('labels_flat({0})'.format(len(labels_flat))) print('labels_flat[{0}] => {1}'.format(Image_to_display, labels_flat[Image_to_display])) labels_count = np.unique(labels_flat).shape[0] print('labels_count => {0}'.format(labels_count))

從運行結(jié)果來看,圖片的數(shù)字為5。
-
然后對數(shù)據(jù)進行 one-hot 編碼處理
# 對數(shù)據(jù)進行 one-hot 編碼 # 0 => [1 0 0 0 0 0 0 0 0 0] # 1 => [0 1 0 0 0 0 0 0 0 0] # ... # 9 => [0 0 0 0 0 0 0 0 0 1] def dense_to_one_hot(labels_dense, num_classes): num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) # flat就是相當(dāng)于變成一維數(shù)組,再讀取 # ravel將多維數(shù)組轉(zhuǎn)化為一維,返回一個連續(xù)的平整的數(shù)組。 labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot labels = dense_to_one_hot(labels_flat, labels_count) labels = labels.astype(np.uint8) # print('labels({0[0]}, {0[1]})'.format(labels.shape)) # print('labels[{0}] => {1}'.format(Image_to_display, labels[Image_to_display])) -
我們還需要把訓(xùn)練數(shù)據(jù)劃分出一個驗證集,來證明我們所做的模型是否有泛化能力。
# 數(shù)據(jù)集的切分 validation_images = images[:2000] validation_labels = labels[:2000] train_images = images[2000:] train_labels = labels[2000:] print('train_images({0[0]}, {0[1]})'.format(train_images.shape)) print('train_labels({0[0]}, {0[1]})'.format(train_labels.shape))

-
接下來就是構(gòu)建Tensorflow圖,我們想要構(gòu)建兩個卷積層,所以要對權(quán)值W進行初始化。而且我們選Relu作為我們的激活函數(shù)。由于Relu的特性,容易產(chǎn)生“死”的神經(jīng)元,所以我們初始化偏置為較小的整數(shù)。
# 建立神經(jīng)網(wǎng)絡(luò) # 權(quán)重初始化 def weight_variable(shape): # 注:tensor 需要初始化,需要將數(shù)據(jù)轉(zhuǎn)換為 tensor 支持的格式 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) -
我們選擇0補充層來防止數(shù)據(jù)寬高減小。步長選擇為1。
# 補充層 def con2d(x, W): # x 指輸入;W 指CNN的卷積核;strides 卷積時在圖像上每一維的步長,一般首尾為1,中間為自定義的步長 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') -
定義池化,池化作用有:
1.保持不變性,比如兩張圖有平移,旋轉(zhuǎn),尺度時,通過取最大值(maxpooling)可以使標(biāo)簽相同但是圖像略微不同的圖具有相同的特征。
2.保留主要特征同時減少參數(shù)和計算量,防止過擬合,提高模型的泛化能力。# 池化 def max_pool_2x2(x): # x 指池化輸入,ksize 為池化窗口的大小,strides 為窗口在每一個維度上滑動的步長 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') -
定義占位符
# 定義占位符 x = tf.placeholder(tf.float32, shape=[None, image_size]) y_ = tf.placeholder(tf.float32, shape=[None, labels_count]) -
定義第一層神經(jīng)網(wǎng)絡(luò),第一層神經(jīng)網(wǎng)絡(luò)用了5*5的過濾器,并且卷積層想要預(yù)估出32個特征值,我們可以得出權(quán)重的shape[5, 5, 1, 32].這里第三個數(shù)字是輸入的通道要與上一層的輸出通道值相一致。
# 第一層卷積神經(jīng)網(wǎng)絡(luò),選擇一個5*5的窗口,初始圖像為28*28*1,將圖像分為32個特征圖 W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) image = tf.reshape(x, [-1, image_width, image_height, 1]) # print(image.get_shape()) h_conv1 = tf.nn.relu(con2d(image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # print(h_conv1.get_shape()) # print(h_pool1.get_shape()) -
定義第二層神經(jīng)網(wǎng)絡(luò),第二層卷積層想要預(yù)估出64個特征值,得到權(quán)重的shape[5, 5, 32, 64]。因為經(jīng)過池化層,圖像已經(jīng)變成了14*14的大小,第二層卷幾層想要得到更一般的特征,過濾器覆蓋了圖像的更多空間,所以我們調(diào)整選擇使用更多的特征。
# 第二層卷積神經(jīng)網(wǎng)絡(luò) W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(con2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # print(h_conv2.get_shape()) # print(h_pool2.get_shape()) -
定義全連接層
# 定義全連接層 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) # print(h_pool2_flat.get_shape()) # print(h_fc1.get_shape()) -
防止過擬合,加入了隨機失活。
# 防止過擬合,隨機殺死一些神經(jīng)元 keep_prob = tf.placeholder('float') # 保存率 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) -
最后使用softmax來得到各分類的預(yù)測分?jǐn)?shù)。
W_fc2 = weight_variable([1024, labels_count]) b_fc2 = bias_variable([labels_count]) # 使用softmax來得到各分類的預(yù)測分?jǐn)?shù) y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # print(y.get_shape()) -
為了使用反向傳播來更新權(quán)值,我們需要定義損失函數(shù),這里我們使用了交叉熵。還需要定義一個優(yōu)化方法,選擇了Adam算法。
# 損失函數(shù),這里使用了交叉熵 cross_entropy = -tf.reduce_sum(y_*tf.log(y)) # 優(yōu)化函數(shù) train_step = tf.train.AdamOptimizer(Learning_rate).minimize(cross_entropy) # 評估 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float')) -
最后預(yù)測屬于哪個數(shù)字。
# 預(yù)測函數(shù) predict = tf.argmax(y,1) -
訓(xùn)練,驗證,預(yù)測
# 訓(xùn)練,驗證,預(yù)測 epochs_completed = 0 index_in_epoch = 0 num_examples = train_images.shape[0] # 按 batch 迭代數(shù)據(jù) def next_batch(batch_size): global train_images global train_labels global index_in_epoch global epochs_completed start = index_in_epoch index_in_epoch += batch_size # 當(dāng)所有訓(xùn)練數(shù)據(jù)都已被使用時,它會被隨機重新排序 if index_in_epoch > num_examples: epochs_completed += 1 # 沖洗數(shù)據(jù) perm = np.arange(num_examples) np.random.shuffle(perm) train_images = train_images[perm] train_labels = train_labels[perm] start = 0 index_in_epoch = batch_size assert batch_size <= num_examples end = index_in_epoch return train_images[start:end], train_labels[start:end] -
做好上面工作后,我們可以啟動tensorflow,這一步絕對不能少。
init = tf.initialize_all_variables() sess = tf.InteractiveSession() sess.run(init) -
接下來,開始訓(xùn)練。
# 變量可視化 train_accuracies = [] validation_accuracies = [] x_range = [] display_step = 1 # 迭代多次,需要 next_batch for i in range(Training_iterations): # 獲得新的批次 batch_xs, batch_ys = next_batch(Batch_size) # 判斷每一步的進度 if i%display_step == 0 or (i+1) == Training_iterations: # 傳入 x,y_ train_accuracy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0}) if (Validation_size): validation_accuracy = accuracy.eval(feed_dict={x: validation_images[0: Batch_size], y_: validation_labels[0: Batch_size], keep_prob: 1.0}) print('train_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy, validation_accuracy, i)) validation_accuracies.append(validation_accuracy) else: print('training_accuracy => %.4f for step %d'%(train_accuracy, i)) train_accuracies.append(train_accuracy) x_range.append(i) # 增加顯示步驟 if i%(display_step*10) ==0 and i: display_step *= 10 # 批量訓(xùn)練 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: Dropout})
從圖中可以看出訓(xùn)練的結(jié)果準(zhǔn)確率大概只有98%。
-
用matplotlib畫出train和validation的準(zhǔn)確度。
# 檢測 train 和 validation 的準(zhǔn)確度 if (Validation_size): validation_accuracy = accuracy.eval(feed_dict = {x: validation_images, y_: validation_labels, keep_prob:1.0}) plt.plot(x_range, train_accuracies, '-b', label='Training') plt.plot(x_range, validation_accuracies, '-g', label='Validation') plt.legend(loc='lower right', frameon=False) plt.ylim(top=1.1, bottom=0.7) plt.ylabel('accuracy') plt.xlabel('step') plt.show()
