您好,登錄后才能下訂單哦!
TensorFlow實現(xiàn)CNN的方法?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
第1步:加載相應(yīng)的庫并創(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數(shù)據(jù)集,這里采用TensorFlow自帶數(shù)據(jù)集,MNIST數(shù)據(jù)為28×28的圖像,因此將其轉(zhuǎn)化為相應(yīng)二維矩陣
#數(shù)據(jù)集 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步:設(shè)置模型參數(shù)
這里采用隨機批量訓(xùn)練的方法,每訓(xùn)練10次對測試集進行測試,共迭代1500次,學(xué)習(xí)率采用指數(shù)下降的方式,初始學(xué)習(xí)率為0.1,每訓(xùn)練10次,學(xué)習(xí)率乘0.9,為了進行對比,后面會給出固定學(xué)習(xí)率為0.01的損失曲線圖和準(zhǔn)確率圖
#設(shè)置模型參數(shù) batch_size = 100 #批量訓(xùn)練圖像張數(shù) initial_learning_rate = 0.1 #學(xué)習(xí)率 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 #測試圖像張數(shù) image_width = 28 #圖像的寬和高 image_height = 28 target_size = 10 #圖像的目標(biāo)為0~9共10個目標(biāo) num_channels = 1 #灰度圖,顏色通道為1 generations = 1500 #迭代500次 evaluation_step = 10 #每訓(xùn)練十次進行一次測試 conv1_features = 25 #卷積層的特征個數(shù) conv2_features = 50 max_pool_size1 = 2 #池化層大小 max_pool_size2 = 2 fully_connected_size = 100 #全連接層的神經(jīng)元個數(shù)
第4步:聲明占位符,注意這里的目標(biāo)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步:聲明卷積層和全連接層的權(quán)重和偏置,這里采用2層卷積層和1層隱含全連接層
#聲明卷積層的權(quán)重和偏置 #卷積層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)) #聲明全連接層權(quán)重和偏置 #卷積層過后圖像的寬和高 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的結(jié)構(gòu),步長為[1,1,1,1],padding為SAME
全連接層隱層神經(jīng)元為100個,輸出層為目標(biāo)個數(shù)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') #全連接層 #先將數(shù)據(jù)轉(zhuǎn)化為1*N的形式 #獲取數(shù)據(jù)大小 conv_output_shape = max_pool2.get_shape().as_list() #全連接層輸入數(shù)據(jù)大小 fully_input_size = conv_output_shape[1]*conv_output_shape[2]*conv_output_shape[3] #這三個shape就是圖像的寬高和通道數(shù) full1_input_data = tf.reshape(max_pool2,[conv_output_shape[0],fully_input_size]) #轉(zhuǎn)化為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步:定義損失函數(shù),這里采用softmax函數(shù)作為損失函數(shù)
#損失函數(shù) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output,labels=y_target))
第8步:建立測評與評估函數(shù),這里對輸出層進行softmax,再通過np.argmax找出每行最大的數(shù)所在位置,再與目標(biāo)值進行比對,統(tǒng)計準(zhǔn)確率
#預(yù)測與評估 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)#返回每行最大的數(shù)所在位置 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步:隨機批量訓(xùn)練并進行繪圖
#開始訓(xùn)練 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') #畫準(zhǔn)確度曲線 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])) #畫學(xué)習(xí)率 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()
下面給出固定學(xué)習(xí)率圖像和學(xué)習(xí)率隨迭代次數(shù)下降的圖像:
首先給出固定學(xué)習(xí)率圖像:
下面是損失曲線
下面是準(zhǔn)確率
我們可以看出,固定學(xué)習(xí)率損失函數(shù)下降速度較緩,同時其最終準(zhǔn)確率為80%~90%之間就不再提高了
下面給出學(xué)習(xí)率隨迭代次數(shù)降低的曲線:
首先給出學(xué)習(xí)率隨迭代次數(shù)降低的損失曲線
然后給出相應(yīng)的準(zhǔn)確率曲線
我們可以看出其損失函數(shù)下降很快,同時準(zhǔn)確率也可以達到90%以上
下面給出隨機抓取的圖像相應(yīng)的識別情況:
至此我們實現(xiàn)了簡單的CNN來實現(xiàn)MNIST手寫圖數(shù)據(jù)集的識別,如果想進一步提高其準(zhǔn)確率,可以通過改變CNN網(wǎng)絡(luò)參數(shù),如通道數(shù)、全連接層神經(jīng)元個數(shù),過濾器大小,學(xué)習(xí)率,訓(xùn)練次數(shù),加入dropout層等等,也可以通過增加CNN網(wǎng)絡(luò)深度來進一步提高其準(zhǔn)確率
下面給出一組參數(shù):
初始學(xué)習(xí)率:initial_learning_rate=0.05
迭代步長:decay_steps=50,每50步改變一次學(xué)習(xí)率
下面是仿真結(jié)果:
關(guān)于TensorFlow實現(xiàn)CNN的方法問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。