TensorFlow實現(xiàn)簡單的CNN的方法
這里,我們將采用Tensor Flow內建函數實現(xiàn)簡單的CNN,并用MNIST數據集進行測試
第1步:加載相應的庫并創(chuàng)建計算圖會話
import numpy as np import tensorflow as tf from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets import matplotlib.pyplot as plt #創(chuàng)建計算圖會話 sess = tf.Session()
第2步:加載MNIST數據集,這里采用TensorFlow自帶數據集,MNIST數據為28×28的圖像,因此將其轉化為相應二維矩陣
#數據集 data_dir = 'MNIST_data' mnist = read_data_sets(data_dir) train_xdata = np.array([np.reshape(x,[28,28]) for x in mnist.train.images] ) test_xdata = np.array([np.reshape(x,[28,28]) for x in mnist.test.images] ) train_labels = mnist.train.labels test_labels = mnist.test.labels
第3步:設置模型參數
這里采用隨機批量訓練的方法,每訓練10次對測試集進行測試,共迭代1500次,學習率采用指數下降的方式,初始學習率為0.1,每訓練10次,學習率乘0.9,為了進行對比,后面會給出固定學習率為0.01的損失曲線圖和準確率圖
#設置模型參數
batch_size = 100 #批量訓練圖像張數
initial_learning_rate = 0.1 #學習率
global_step = tf.Variable(0, trainable=False) ;
learning_rate = tf.train.exponential_decay(initial_learning_rate,
global_step=global_step,
decay_steps=10,decay_rate=0.9)
evaluation_size = 500 #測試圖像張數
image_width = 28 #圖像的寬和高
image_height = 28
target_size = 10 #圖像的目標為0~9共10個目標
num_channels = 1 #灰度圖,顏色通道為1
generations = 1500 #迭代500次
evaluation_step = 10 #每訓練十次進行一次測試
conv1_features = 25 #卷積層的特征個數
conv2_features = 50
max_pool_size1 = 2 #池化層大小
max_pool_size2 = 2
fully_connected_size = 100 #全連接層的神經元個數
第4步:聲明占位符,注意這里的目標y_target類型為int32整型
#聲明占位符 x_input_shape = [batch_size,image_width,image_height,num_channels] x_input = tf.placeholder(tf.float32,shape=x_input_shape) y_target = tf.placeholder(tf.int32,shape=[batch_size]) evaluation_input_shape = [evaluation_size,image_width,image_height,num_channels] evaluation_input = tf.placeholder(tf.float32,shape=evaluation_input_shape) evaluation_target = tf.placeholder(tf.int32,shape=[evaluation_size])
第5步:聲明卷積層和全連接層的權重和偏置,這里采用2層卷積層和1層隱含全連接層
#聲明卷積層的權重和偏置 #卷積層1 #采用濾波器為4X4濾波器,輸入通道為1,輸出通道為25 conv1_weight = tf.Variable(tf.truncated_normal([4,4,num_channels,conv1_features],stddev=0.1,dtype=tf.float32)) conv1_bias = tf.Variable(tf.truncated_normal([conv1_features],stddev=0.1,dtype=tf.float32)) #卷積層2 #采用濾波器為4X4濾波器,輸入通道為25,輸出通道為50 conv2_weight = tf.Variable(tf.truncated_normal([4,4,conv1_features,conv2_features],stddev=0.1,dtype=tf.float32)) conv2_bias = tf.Variable(tf.truncated_normal([conv2_features],stddev=0.1,dtype=tf.float32)) #聲明全連接層權重和偏置 #卷積層過后圖像的寬和高 conv_output_width = image_width // (max_pool_size1 * max_pool_size2) #//表示整除 conv_output_height = image_height // (max_pool_size1 * max_pool_size2) #全連接層的輸入大小 full1_input_size = conv_output_width * conv_output_height *conv2_features full1_weight = tf.Variable(tf.truncated_normal([full1_input_size,fully_connected_size],stddev=0.1,dtype=tf.float32)) full1_bias = tf.Variable(tf.truncated_normal([fully_connected_size],stddev=0.1,dtype=tf.float32)) full2_weight = tf.Variable(tf.truncated_normal([fully_connected_size,target_size],stddev=0.1,dtype=tf.float32)) full2_bias = tf.Variable(tf.truncated_normal([target_size],stddev=0.1,dtype=tf.float32))
第6步:聲明CNN模型,這里的兩層卷積層均采用Conv-ReLU-MaxPool的結構,步長為[1,1,1,1],padding為SAME
全連接層隱層神經元為100個,輸出層為目標個數10
def my_conv_net(input_data):
#第一層:Conv-ReLU-MaxPool
conv1 = tf.nn.conv2d(input_data,conv1_weight,strides=[1,1,1,1],padding='SAME')
relu1 = tf.nn.relu(tf.nn.bias_add(conv1,conv1_bias))
max_pool1 = tf.nn.max_pool(relu1,ksize=[1,max_pool_size1,max_pool_size1,1],strides=[1,max_pool_size1,max_pool_size1,1],padding='SAME')
#第二層:Conv-ReLU-MaxPool
conv2 = tf.nn.conv2d(max_pool1, conv2_weight, strides=[1, 1, 1, 1], padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_bias))
max_pool2 = tf.nn.max_pool(relu2, ksize=[1, max_pool_size2, max_pool_size2, 1],
strides=[1, max_pool_size2, max_pool_size2, 1], padding='SAME')
#全連接層
#先將數據轉化為1*N的形式
#獲取數據大小
conv_output_shape = max_pool2.get_shape().as_list()
#全連接層輸入數據大小
fully_input_size = conv_output_shape[1]*conv_output_shape[2]*conv_output_shape[3] #這三個shape就是圖像的寬高和通道數
full1_input_data = tf.reshape(max_pool2,[conv_output_shape[0],fully_input_size]) #轉化為batch_size*fully_input_size二維矩陣
#第一層全連接
fully_connected1 = tf.nn.relu(tf.add(tf.matmul(full1_input_data,full1_weight),full1_bias))
#第二層全連接輸出
model_output = tf.nn.relu(tf.add(tf.matmul(fully_connected1,full2_weight),full2_bias))#shape = [batch_size,target_size]
return model_output
model_output = my_conv_net(x_input)
test_model_output = my_conv_net(evaluation_input)
第7步:定義損失函數,這里采用softmax函數作為損失函數
#損失函數 loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output,labels=y_target))
第8步:建立測評與評估函數,這里對輸出層進行softmax,再通過np.argmax找出每行最大的數所在位置,再與目標值進行比對,統(tǒng)計準確率
#預測與評估 prediction = tf.nn.softmax(model_output) test_prediction = tf.nn.softmax(test_model_output) def get_accuracy(logits,targets): batch_predictions = np.argmax(logits,axis=1)#返回每行最大的數所在位置 num_correct = np.sum(np.equal(batch_predictions,targets)) return 100*num_correct/batch_predictions.shape[0]
第9步:初始化模型變量并創(chuàng)建優(yōu)化器
#創(chuàng)建優(yōu)化器 opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) train_step = opt.minimize(loss) #初始化變量 init = tf.initialize_all_variables() sess.run(init)
第10步:隨機批量訓練并進行繪圖
#開始訓練
train_loss = []
train_acc = []
test_acc = []
Learning_rate_vec = []
for i in range(generations):
rand_index = np.random.choice(len(train_xdata),size=batch_size)
rand_x = train_xdata[rand_index]
rand_x = np.expand_dims(rand_x,3)
rand_y = train_labels[rand_index]
Learning_rate_vec.append(sess.run(learning_rate, feed_dict={global_step: i}))
train_dict = {x_input:rand_x,y_target:rand_y}
sess.run(train_step,feed_dict={x_input:rand_x,y_target:rand_y,global_step:i})
temp_train_loss = sess.run(loss,feed_dict=train_dict)
temp_train_prediction = sess.run(prediction,feed_dict=train_dict)
temp_train_acc = get_accuracy(temp_train_prediction,rand_y)
#測試集
if (i+1)%evaluation_step ==0:
eval_index = np.random.choice(len(test_xdata),size=evaluation_size)
eval_x = test_xdata[eval_index]
eval_x = np.expand_dims(eval_x,3)
eval_y = test_labels[eval_index]
test_dict = {evaluation_input:eval_x,evaluation_target:eval_y}
temp_test_preds = sess.run(test_prediction,feed_dict=test_dict)
temp_test_acc = get_accuracy(temp_test_preds,eval_y)
test_acc.append(temp_test_acc)
train_acc.append(temp_train_acc)
train_loss.append(temp_train_loss)
#畫損失曲線
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(train_loss,'k-')
ax.set_xlabel('Generation')
ax.set_ylabel('Softmax Loss')
fig.suptitle('Softmax Loss per Generation')
#畫準確度曲線
index = np.arange(start=1,stop=generations+1,step=evaluation_step)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(train_acc,'k-',label='Train Set Accuracy')
ax2.plot(index,test_acc,'r--',label='Test Set Accuracy')
ax2.set_xlabel('Generation')
ax2.set_ylabel('Accuracy')
fig2.suptitle('Train and Test Set Accuracy')
#畫圖
fig3 = plt.figure()
actuals = rand_y[0:6]
train_predictions = np.argmax(temp_train_prediction,axis=1)[0:6]
images = np.squeeze(rand_x[0:6])
Nrows = 2
Ncols =3
for i in range(6):
ax3 = fig3.add_subplot(Nrows,Ncols,i+1)
ax3.imshow(np.reshape(images[i],[28,28]),cmap='Greys_r')
ax3.set_title('Actual: '+str(actuals[i]) +' pred: '+str(train_predictions[i]))
#畫學習率
fig4 = plt.figure()
ax4 = fig4.add_subplot(111)
ax4.plot(Learning_rate_vec,'k-')
ax4.set_xlabel('step')
ax4.set_ylabel('Learning_rate')
fig4.suptitle('Learning_rate')
plt.show()
下面給出固定學習率圖像和學習率隨迭代次數下降的圖像:
首先給出固定學習率圖像:
下面是損失曲線

下面是準確率

我們可以看出,固定學習率損失函數下降速度較緩,同時其最終準確率為80%~90%之間就不再提高了
下面給出學習率隨迭代次數降低的曲線:
首先給出學習率隨迭代次數降低的損失曲線

然后給出相應的準確率曲線

我們可以看出其損失函數下降很快,同時準確率也可以達到90%以上
下面給出隨機抓取的圖像相應的識別情況:

至此我們實現(xiàn)了簡單的CNN來實現(xiàn)MNIST手寫圖數據集的識別,如果想進一步提高其準確率,可以通過改變CNN網絡參數,如通道數、全連接層神經元個數,過濾器大小,學習率,訓練次數,加入dropout層等等,也可以通過增加CNN網絡深度來進一步提高其準確率
下面給出一組參數:
初始學習率:initial_learning_rate=0.05
迭代步長:decay_steps=50,每50步改變一次學習率
下面是仿真結果:




我們可以看出,通過調整超參數,其既保證了損失函數能夠快速下降,又進一步提高了其模型準確率,我們在訓練次數為1500次的基礎上,準確率已經達到97%以上。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
django開發(fā)之settings.py中變量的全局引用詳解
當網站里面的一些內容,如郵箱,網站標題,網站的描述,這些東西我們可以存在數據庫中也可以存放在我們的setting 文件中,這篇文章主要給大家介紹了django中settings.py變量的全局引用的相關資料,文中介紹的非常詳細,需要的朋友可以參考下。2017-03-03
Django 項目通過加載不同env文件來區(qū)分不同環(huán)境
這篇文章主要介紹了Django 項目如何通過加載不同env文件來區(qū)分不同環(huán)境,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
python可擴展的Blender 3D插件開發(fā)匯總
這篇文章主要為大家介紹了python可擴展的Blender 3D插件開發(fā)匯總,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
python shapely.geometry.polygon任意兩個四邊形的IOU計算實例
這篇文章主要介紹了python shapely.geometry.polygon任意兩個四邊形的IOU計算實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04

