這里使用的數據集仍然是CIFAR-10,由於之前寫過一篇使用AlexNet對CIFAR數據集進行分類的文章,已經詳細介紹了這個數據集,當時我們是直接把這些圖片的數據文件下載下來,然后使用pickle進行反序列化獲取數據的,具體內容可以參考這里:第十六節,卷積神經網絡之AlexNet網絡實現(六)
與MNIST類似,TensorFlow中也有一個下載和導入CIFAR數據集的代碼文件,不同的是,自從TensorFlow1.0之后,將里面的Models模塊分離了出來,分離和導入CIFAR數據集的代碼在models中,所以要先去TensorFlow的GitHub網站將其下載下來。點擊下載地址開始下載。

一 描述
在該例子中,使用了全局平均池化層來代替傳統的全連接層,使用了3個卷積層的同卷積網絡,濾波器為5x5,每個卷積層后面跟有一個步長2x2的池化層,濾波器大小為2x2,最后一個池化層為全局平均池化層,輸出后為batch_sizex1x1x10,我們對其進行形狀變換為batch_sizex10,得到10個特征,再對這10個特征進行softmax計算,其結果代表最終分類。
- 輸入圖片大小為24x24x3
- 經過5x5的同卷積操作(步長為1),輸出64個通道,得到24x24x64的輸出
- 經過f=2,s=2的池化層,得到大小為12x12x24的輸出
- 經過5x5的同卷積操作(步長為1),輸出64個通道,得到12x12x64的輸出
- 經過f=2,s=2的池化層,得到大小為6x6x64的輸出
- 經過5x5的同卷積操作(步長為1),輸出10個通道,得到6x6x10的輸出
- 經過一個全局平均池化層f=6,s=6,得到1x1x10的輸出
- 展開成1x10的形狀,經過softmax函數計算,進行分類
二 導入數據集
''' 一 引入數據集 ''' batch_size = 128 learning_rate = 1e-4 training_step = 15000 display_step = 200 #數據集目錄 data_dir = './cifar10_data/cifar-10-batches-bin' print('begin') #獲取訓練集數據 images_train,labels_train = cifar10_input.inputs(eval_data=False,data_dir = data_dir,batch_size=batch_size) print('begin data')
注意這里調用了cifar10_input.inputs()函數,這個函數是專門獲取數據的函數,返回數據集合對應的標簽,但是這個函數會將圖片裁切好,由原來的32x32x3變成24x24x3,該函數默認使用測試數據集,如果使用訓練數據集,可以將第一個參數傳入eval_data=False。另外再將batch_size和dir傳入,就可以得到dir下面的batch_size個數據了。我們可以查看一下這個函數的實現:
def inputs(eval_data, data_dir, batch_size): """Construct input for CIFAR evaluation using the Reader ops. Args: eval_data: bool, indicating if one should use the train or eval data set. data_dir: Path to the CIFAR-10 data directory. batch_size: Number of images per batch. Returns: images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. labels: Labels. 1D tensor of [batch_size] size. """ if not eval_data: filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i) for i in xrange(1, 6)] num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN else: filenames = [os.path.join(data_dir, 'test_batch.bin')] num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_EVAL for f in filenames: if not tf.gfile.Exists(f): raise ValueError('Failed to find file: ' + f) with tf.name_scope('input'): # Create a queue that produces the filenames to read. filename_queue = tf.train.string_input_producer(filenames) # Read examples from files in the filename queue. read_input = read_cifar10(filename_queue) reshaped_image = tf.cast(read_input.uint8image, tf.float32) height = IMAGE_SIZE width = IMAGE_SIZE # Image processing for evaluation. # Crop the central [height, width] of the image. resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image, height, width) # Subtract off the mean and divide by the variance of the pixels. float_image = tf.image.per_image_standardization(resized_image) # Set the shapes of tensors. float_image.set_shape([height, width, 3]) read_input.label.set_shape([1]) # Ensure that the random shuffling has good mixing properties. min_fraction_of_examples_in_queue = 0.4 min_queue_examples = int(num_examples_per_epoch * min_fraction_of_examples_in_queue) # Generate a batch of images and labels by building up a queue of examples. return _generate_image_and_label_batch(float_image, read_input.label, min_queue_examples, batch_size, shuffle=False)
這個函數主要包含以下幾步:
- 讀取測試集文件名或者訓練集文件名,並創建文件名隊列。
- 使用文件讀取器讀取一張圖像的數據和標簽,並返回一個存放這些張量數據的類對象。
- 對圖像進行裁切處理。
- 歸一化輸入。
- 讀取batch_size個圖像和標簽。(返回的是一個張量,必須要在會話中執行才能得到數據)
三 定義網絡結構
''' 二 定義網絡結構 ''' def weight_variable(shape): ''' 初始化權重 args: shape:權重shape ''' initial = tf.truncated_normal(shape=shape,mean=0.0,stddev=0.1) return tf.Variable(initial) def bias_variable(shape): ''' 初始化偏置 args: shape:偏置shape ''' initial =tf.constant(0.1,shape=shape) return tf.Variable(initial) def conv2d(x,W): ''' 卷積運算 ,使用SAME填充方式 卷積層后 out_height = in_hight / strides_height(向上取整) out_width = in_width / strides_width(向上取整) args: x:輸入圖像 形狀為[batch,in_height,in_width,in_channels] W:權重 形狀為[filter_height,filter_width,in_channels,out_channels] ''' return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME') def max_pool_2x2(x): ''' 最大池化層,濾波器大小為2x2,'SAME'填充方式 池化層后 out_height = in_hight / strides_height(向上取整) out_width = in_width / strides_width(向上取整) args: x:輸入圖像 形狀為[batch,in_height,in_width,in_channels] ''' return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') def avg_pool_6x6(x): ''' 全局平均池化層,使用一個與原有輸入同樣尺寸的filter進行池化,'SAME'填充方式 池化層后 out_height = in_hight / strides_height(向上取整) out_width = in_width / strides_width(向上取整) args; x:輸入圖像 形狀為[batch,in_height,in_width,in_channels] ''' return tf.nn.avg_pool(x,ksize=[1,6,6,1],strides=[1,6,6,1],padding='SAME') def print_op_shape(t): ''' 輸出一個操作op節點的形狀 ''' print(t.op.name,'',t.get_shape().as_list()) #定義占位符 input_x = tf.placeholder(dtype=tf.float32,shape=[None,24,24,3]) #圖像大小24x24x input_y = tf.placeholder(dtype=tf.float32,shape=[None,10]) #0-9類別 x_image = tf.reshape(input_x,[-1,24,24,3]) #1.卷積層 ->池化層 W_conv1 = weight_variable([5,5,3,64]) b_conv1 = bias_variable([64]) h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1) #輸出為[-1,24,24,64] print_op_shape(h_conv1) h_pool1 = max_pool_2x2(h_conv1) #輸出為[-1,12,12,64] print_op_shape(h_pool1) #2.卷積層 ->池化層 W_conv2 = weight_variable([5,5,64,64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) #輸出為[-1,12,12,64] print_op_shape(h_conv2) h_pool2 = max_pool_2x2(h_conv2) #輸出為[-1,6,6,64] print_op_shape(h_pool2) #3.卷積層 ->全局平均池化層 W_conv3 = weight_variable([5,5,64,10]) b_conv3 = bias_variable([10]) h_conv3 = tf.nn.relu(conv2d(h_pool2,W_conv3) + b_conv3) #輸出為[-1,6,6,10] print_op_shape(h_conv3) nt_hpool3 = avg_pool_6x6(h_conv3) #輸出為[-1,1,1,10] print_op_shape(nt_hpool3) nt_hpool3_flat = tf.reshape(nt_hpool3,[-1,10]) y_conv = tf.nn.softmax(nt_hpool3_flat)
四 定義求解器
''' 三 定義求解器 ''' #softmax交叉熵代價函數 cost = tf.reduce_mean(-tf.reduce_sum(input_y * tf.log(y_conv),axis=1)) #求解器 train = tf.train.AdamOptimizer(learning_rate).minimize(cost) #返回一個准確度的數據 correct_prediction = tf.equal(tf.arg_max(y_conv,1),tf.arg_max(input_y,1)) #准確率 accuracy = tf.reduce_mean(tf.cast(correct_prediction,dtype=tf.float32))
五 開始測試
''' 四 開始訓練 ''' sess = tf.Session(); sess.run(tf.global_variables_initializer()) # 啟動計算圖中所有的隊列線程 調用tf.train.start_queue_runners來將文件名填充到隊列,否則read操作會被阻塞到文件名隊列中有值為止。 tf.train.start_queue_runners(sess=sess) for step in range(training_step): #獲取batch_size大小數據集 image_batch,label_batch = sess.run([images_train,labels_train]) #one hot編碼 label_b = np.eye(10,dtype=np.float32)[label_batch] #開始訓練 train.run(feed_dict={input_x:image_batch,input_y:label_b},session=sess) if step % display_step == 0: train_accuracy = accuracy.eval(feed_dict={input_x:image_batch,input_y:label_b},session=sess) print('Step {0} tranining accuracy {1}'.format(step,train_accuracy))


我們可以看到這個模型准確率接近70%,這主要是因為我們在圖像預處理是進行了輸入歸一化處理,導致比我們在第十六節,卷積神經網絡之AlexNet網絡實現(六)文章中使用傳統神經網絡訓練准確度52%要提高了不少,並且比AlexNet的60%高了一些(AlexNet我迭代的輪數比較少,因為太耗時)。
完整代碼:
# -*- coding: utf-8 -*- """ Created on Thu May 3 12:29:16 2018 @author: zy """ ''' 建立一個帶有全局平均池化層的卷積神經網絡 並對CIFAR-10數據集進行分類 1.使用3個卷積層的同卷積操作,濾波器大小為5x5,每個卷積層后面都會跟一個步長為2x2的池化層,濾波器大小為2x2 2.對輸出的10個feature map進行全局平均池化,得到10個特征 3.對得到的10個特征進行softmax計算,得到分類 ''' import cifar10_input import tensorflow as tf import numpy as np ''' 一 引入數據集 ''' batch_size = 128 learning_rate = 1e-4 training_step = 15000 display_step = 200 #數據集目錄 data_dir = './cifar10_data/cifar-10-batches-bin' print('begin') #獲取訓練集數據 images_train,labels_train = cifar10_input.inputs(eval_data=False,data_dir = data_dir,batch_size=batch_size) print('begin data') ''' 二 定義網絡結構 ''' def weight_variable(shape): ''' 初始化權重 args: shape:權重shape ''' initial = tf.truncated_normal(shape=shape,mean=0.0,stddev=0.1) return tf.Variable(initial) def bias_variable(shape): ''' 初始化偏置 args: shape:偏置shape ''' initial =tf.constant(0.1,shape=shape) return tf.Variable(initial) def conv2d(x,W): ''' 卷積運算 ,使用SAME填充方式 池化層后 out_height = in_hight / strides_height(向上取整) out_width = in_width / strides_width(向上取整) args: x:輸入圖像 形狀為[batch,in_height,in_width,in_channels] W:權重 形狀為[filter_height,filter_width,in_channels,out_channels] ''' return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME') def max_pool_2x2(x): ''' 最大池化層,濾波器大小為2x2,'SAME'填充方式 池化層后 out_height = in_hight / strides_height(向上取整) out_width = in_width / strides_width(向上取整) args: x:輸入圖像 形狀為[batch,in_height,in_width,in_channels] ''' return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') def avg_pool_6x6(x): ''' 全局平均池化層,使用一個與原有輸入同樣尺寸的filter進行池化,'SAME'填充方式 池化層后 out_height = in_hight / strides_height(向上取整) out_width = in_width / strides_width(向上取整) args; x:輸入圖像 形狀為[batch,in_height,in_width,in_channels] ''' return tf.nn.avg_pool(x,ksize=[1,6,6,1],strides=[1,6,6,1],padding='SAME') def print_op_shape(t): ''' 輸出一個操作op節點的形狀 ''' print(t.op.name,'',t.get_shape().as_list()) #定義占位符 input_x = tf.placeholder(dtype=tf.float32,shape=[None,24,24,3]) #圖像大小24x24x input_y = tf.placeholder(dtype=tf.float32,shape=[None,10]) #0-9類別 x_image = tf.reshape(input_x,[-1,24,24,3]) #1.卷積層 ->池化層 W_conv1 = weight_variable([5,5,3,64]) b_conv1 = bias_variable([64]) h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1) #輸出為[-1,24,24,64] print_op_shape(h_conv1) h_pool1 = max_pool_2x2(h_conv1) #輸出為[-1,12,12,64] print_op_shape(h_pool1) #2.卷積層 ->池化層 W_conv2 = weight_variable([5,5,64,64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) #輸出為[-1,12,12,64] print_op_shape(h_conv2) h_pool2 = max_pool_2x2(h_conv2) #輸出為[-1,6,6,64] print_op_shape(h_pool2) #3.卷積層 ->全局平均池化層 W_conv3 = weight_variable([5,5,64,10]) b_conv3 = bias_variable([10]) h_conv3 = tf.nn.relu(conv2d(h_pool2,W_conv3) + b_conv3) #輸出為[-1,6,6,10] print_op_shape(h_conv3) nt_hpool3 = avg_pool_6x6(h_conv3) #輸出為[-1,1,1,10] print_op_shape(nt_hpool3) nt_hpool3_flat = tf.reshape(nt_hpool3,[-1,10]) y_conv = tf.nn.softmax(nt_hpool3_flat) ''' 三 定義求解器 ''' #softmax交叉熵代價函數 cost = tf.reduce_mean(-tf.reduce_sum(input_y * tf.log(y_conv),axis=1)) #求解器 train = tf.train.AdamOptimizer(learning_rate).minimize(cost) #返回一個准確度的數據 correct_prediction = tf.equal(tf.arg_max(y_conv,1),tf.arg_max(input_y,1)) #准確率 accuracy = tf.reduce_mean(tf.cast(correct_prediction,dtype=tf.float32)) ''' 四 開始訓練 ''' sess = tf.Session(); sess.run(tf.global_variables_initializer()) tf.train.start_queue_runners(sess=sess) for step in range(training_step): image_batch,label_batch = sess.run([images_train,labels_train]) label_b = np.eye(10,dtype=np.float32)[label_batch] train.run(feed_dict={input_x:image_batch,input_y:label_b},session=sess) if step % display_step == 0: train_accuracy = accuracy.eval(feed_dict={input_x:image_batch,input_y:label_b},session=sess) print('Step {0} tranining accuracy {1}'.format(step,train_accuracy))
