機器學習筆記:tensorflow實現卷積神經網路經典案例--識別手寫數字
從識別手寫數字的案例開始認識神經網路,並瞭解如何在tensorflow中一步步建立卷積神經網路。
安裝tensorflow
資料來源
kaggle新手入門的數字識別案例,包含手寫0-9的灰度值影象的csv檔案,下載地址:https://www.kaggle.com/c/digit-recognizer/data
檔案裡共有42000個數字影象,每個影象的屬性為長28畫素,寬28畫素,共784個畫素,這個矩陣可表示為一個28*28=784的陣列。每個畫素值的大小表示該畫素的顏色明暗,值位於0-255之間,值越大表明顏色越深。csv檔案的第一列是數字的真實標籤。
Python實現CNN
匯入各個模組和設定引數:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
%matplotlib inline
import tensorflow as tf
#引數設定
learning_rate=1e-4
training_iterations=2000
dropout=0.5
batch_size=50
#所有的訓練樣本分批訓練的效率最高,每一批的訓練樣本數量就是batch
validation_size=2000
image_to_display=10
資料準備:
data=pd.read_csv('.../train.csv' )
images=data.iloc[:,1:].values
images=images.astype(np.float)
#對訓練資料進行歸一化處理,[0:255]=>[0.0:1.0]
images=np.multiply(images,1.0/255.0)
#print('images({0[0]},{0[1]})'.format(images.shape))可以檢視資料格式,輸出結果為'data(42000,784)'
image_size=images.shape[1]
image_width=image_height=np.ceil(np.sqrt(image_size)).astype(np.uint8)
#定義顯示圖片的函式
def display(img):
#從784=>28*28
one_img=img.reshape(image_width,image_height)
plt.axis('off')
plt.imshow(one_img,cmap=cm.binary)
display(images[10])
#顯示資料表格中第十條資料代表的數字,結果如下圖
labels_flat=data.iloc[:,0].values.ravel()
labels_count=np.unique(labels_flat).shape[0]
#定義one-hot編碼函式
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))
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[10])的輸出結果為'[0 0 0 0 0 0 0 0 1 0]',代表資料集中第10個數字的實際值為'8'
#將資料拆分成用於訓練和驗證兩部分
validation_images=images[:validation_size]
#將訓練的資料分為train和validation,validation的部分是為了對比不同模型引數的訓練效果,如:learning_rate, training_iterations, dropout
validation_labels=labels[:validation_size]
train_images = images[validation_size:]
train_labels = labels[validation_size:]
定義權重、偏差、卷積圖層、池化圖層:
#定義weight
def weight_variable(shape):
initial=tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
#定義bias
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')
權重weight和偏置bias其實可以寫成python的輸入量,但是TensorFlow有更好的處理方式,將weight和bias設定成為變數,即計算圖中的一個值,這樣使得它們能夠在計算過程中使用,甚至進行修改。shape表示weight和bias的維度。
卷積使用1步長(strides[1, x_movement,y_movement, 1]),0邊距(padding)的模板,保證輸出和輸入是同一個大小。padding:邊距處理,“SAME”表示輸出圖層和輸入圖層大小保持不變,設定為“VALID”時表示捨棄多餘邊距(會丟失資訊)。
池化用簡單傳統的2x2大小的模板做max pooling, 取切片中的最大值 。
佔位符:
x=tf.placeholder(tf.float32,shape=[None,image_size])
y_=tf.placeholder(tf.float32,shape=[None,labels_count])
我們通過為輸入影象和目標輸出類別建立節點,來開始構建計算圖。
這裡的x和y並不是特定的值,相反,他們都只是一個佔位符,可以在TensorFlow執行某一計算時根據該佔位符輸入具體的值。
輸入圖片x是一個2維的浮點型張量。這裡,它的shape為[None, 784],其中784是一張展平的數字圖片的維度。None表示無論輸入多少樣本資料都可以,在這裡作為第一個維度值,用以指代batch的大小,意即x的數量不定。輸出類別值y_也是一個2維張量,其中每一行是一個10維的one-hot向量,用於代表對應某一數字圖片的類別。
第一層卷積:
W_conv1=weight_variable([5,5,1,32])
#即輸入影象的厚度由1增加到32
b_conv1=bias_variable([32])
#bias的厚度與weight輸出通道數量相同
image=tf.reshape(x,[-1,image_width,image_height,1])
h_conv1=tf.nn.relu(conv2d(image,W_conv1)+b_conv1)
#圖層的大小為28*28*32
h_pool1=max_pool_2x2(h_conv1)
#圖層的大小為14*14*32
第一層卷積層由一個卷積和一個最大池化完成。卷積在每個5x5的patch中算出32個特徵。卷積的權重張量形狀是[5, 5, 1, 32],前兩個維度是patch的大小,接著是輸入的通道數目,最後是輸出的通道數目。 而對於每一個輸出通道都有一個對應的偏置量。
在呼叫資料前,需要將原圖變換為4維:第一維的-1表示資料是黑白的,其第2、第3維對應圖片的寬、高,最後一維代表圖片的顏色通道數(因為是灰度圖所以這裡的通道數為1,如果是RGB彩色圖,則為3);注意這裡的reshape是tf裡的屬性,而不是numpy裡的。
第二層卷積:
W_conv2=weight_variable([5,5,32,64])
#輸入影象的厚度由32增加到64
b_conv2=bias_variable([64])
#bias的厚度與weight相同
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
#圖層的大小為14*14*64
h_pool2=max_pool_2x2(h_conv2)
#圖層的大小為7*7*64
第二層卷積切片的patch為5*5大小,輸入32個通道,輸出64個通道。第一層卷積輸出32個通道,第二層卷積輸出64個通道,32和64的數值是主觀自定義的。
全連線層:
#第一層全連線層
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(tf.float32)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
#第二層全連線層
W_fc2=weight_variable([1024,labels_count])
b_fc2=bias_variable([labels_count])
y=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)
#訓練輸出的y為1*10的向量
在卷積層之後,首先加入一個有1024個神經元的全連線層,用於處理整個圖片。當然,需要先將池化層輸出的張量reshape成1024維(數值1024是主觀選擇的,無相關控制因素)
dropout本質上主要是遮蔽神經元的輸出,keep_prob是不遮蔽的比例,例如:每次隨機刪除20%,那麼keep_prob就是0.8
代價函式、訓練模型、評估模型:
#代價函式
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#優化函式
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'))
predict=tf.argmax(y,1)
為了進行訓練,會用更加複雜的AdamOptimizer來做梯度最速下降。
tf.argmax(y,1)輸出引數指定的維度中的最大值的索引,tf.argmax(y_,1)是實際的標籤,通過tf.equal方法可以比較預測結果與實際結果是否相等,輸出布林值。
tf.cast將布林值轉換成浮點數,如:[True, False, True, True]會轉換成[1,0,1,1],其平均值0.75代表了預測的準確比例
定義next_batch函式,以便自動更迭下一個batch的資料樣本:
epochs_completed = 0
index_in_epoch = 0
num_examples = train_images.shape[0]
# serve data by batches
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
if index_in_epoch > num_examples:
# finished epoch
epochs_completed += 1
# shuffle the data
perm = np.arange(num_examples)
np.random.shuffle(perm)
#np.random.shuffle表示將括號內陣列隨機打亂
train_images = train_images[perm]
train_labels = train_labels[perm]
# start next epoch
start = 0
index_in_epoch = batch_size
#在開發一個程式時候,與其讓它執行時崩潰,不如在它出現錯誤條件時就崩潰(返回錯誤)
end = index_in_epoch
return train_images[start:end], train_labels[start:end]
初始化tensorflow框架的變數:
sess = tf.Session()
sess.run(tf.initialize_all_variables())
Tensorflow依賴於一個更高效的C++後端來進行數值計算,與後端的這個連線叫做session。由於來回切換Python內、外環境需要不小的開銷,所以我們藉助python構建可以在外部執行的計算圖,然後在session中啟動它,讓它在Python外部執行。
為了方便下文,也可以寫成sess = tf.InteractiveSession(),意味著將自己作為預設構建的session,tensor.eval()和operation.run()就會呼叫這預設的session
訓練和評估模型:
train_accuracies = []
validation_accuracies = []
x_range = []
for i in range(training_iterations):
batch_xs, batch_ys = next_batch(batch_size)
if i % 100 == 0:
train_accuracy = accuracy.eval(session = sess, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0})
#如果初始化時是sess = tf.InteractiveSession(),那麼這句和validation_accuracy裡的session = sess就可以省略了
validation_accuracy = accuracy.eval(session = sess,feed_dict={ x: validation_images[0:batch_size], y_: validation_labels[0:batch_size], keep_prob: 1.0})
validation_accuracies.append(validation_accuracy)
train_accuracies.append(train_accuracy)
x_range.append(i)
print('train_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy, validation_accuracy, i))
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: dropout})
一次training_iteration的樣本數量就是batch_size的大小,所以i每加1,next_batch函式就作用一次,batch_xs, batch_ys就變更為下一個50的測試樣本。
訓練中間過程的日誌如下:
WARNING:tensorflow:From :3 in .: 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.
train_accuracy / validation_accuracy => 0.10 / 0.14 for step 0
train_accuracy / validation_accuracy => 0.80 / 0.78 for step 100
train_accuracy / validation_accuracy => 0.94 / 0.90 for step 200
train_accuracy / validation_accuracy => 0.92 / 0.88 for step 300
train_accuracy / validation_accuracy => 0.86 / 0.92 for step 400
train_accuracy / validation_accuracy => 0.98 / 0.90 for step 500
train_accuracy / validation_accuracy => 0.94 / 0.94 for step 600
train_accuracy / validation_accuracy => 0.88 / 0.90 for step 700
train_accuracy / validation_accuracy => 0.96 / 0.90 for step 800
train_accuracy / validation_accuracy => 0.98 / 0.92 for step 900
train_accuracy / validation_accuracy => 1.00 / 0.94 for step 1000
train_accuracy / validation_accuracy => 1.00 / 0.96 for step 1100
train_accuracy / validation_accuracy => 0.94 / 0.96 for step 1200
train_accuracy / validation_accuracy => 1.00 / 0.94 for step 1300
train_accuracy / validation_accuracy => 0.94 / 0.98 for step 1400
train_accuracy / validation_accuracy => 1.00 / 0.98 for step 1500
train_accuracy / validation_accuracy => 0.92 / 1.00 for step 1600
train_accuracy / validation_accuracy => 0.96 / 0.98 for step 1700
train_accuracy / validation_accuracy => 0.96 / 0.98 for step 1800
train_accuracy / validation_accuracy => 0.98 / 0.98 for step 1900
#訓練和驗證的準確率,並作圖顯示
if(validation_size):
validation_accuracy = accuracy.eval(session = sess,feed_dict={x: validation_images, y_: validation_labels, keep_prob: 1.0})
print('validation_accuracy => %.4f'%validation_accuracy)
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(ymax = 1.1, ymin = 0.7)
plt.ylabel('accuracy')
plt.xlabel('step')
plt.show()
validation_accuracy => 0.9825
#匯入測試資料
test_images=pd.read_csv('D://test.csv').values
test_images=test_images.astype(np.float)
#對測試資料進行歸一化處理,從[0:255]=>[0:1]
test_images=np.multiply(test_images,1.0/255.0)
print('test_images({0[0]},{0[1]})'.format(test_images.shape))
validation資料得到的模型精準度為0.9825,在訓練迭代200次之後,資料的validation和train的精確度都高於90%,之後再波動上升。
使用訓練好的模型識別數字:
predict_labels=np.zeros(test_images.shape[0])
for i in range(test_images.shape[0]//batch_size):
predict_labels[i*batch_size : (i+1)*batch_size] = predict.eval(session=sess,feed_dict={x: test_images[i*batch_size : (i+1)*batch_size],keep_prob: 1.0})
#顯示實際數字圖片和模型識別出的數字
display(test_images[image_to_display])
print('predict_label[{0}] is {1}'.format(image_to_display,predict_labels[image_to_display]))
predict_label[10] is 5.0
我們從測試的資料集中畫出了第10位手寫數字是5,然後通過訓練好的模型,識別出的數字也是5,準確的識別出來了,表明我們的識別手寫數字模型訓練的很成功。
留有的疑問:
在最後一段識別的程式碼塊中,predict_labels的語句應該也可以寫成:
predict_labels=sess.run(predict,feed_dict={x:test_images,keep_prob=1.0})這句應該與下一句都能設定predict_labels,但在Jupyter notebook裡執行總是報錯’invalid syntax’,還請各位大神不吝賜教。