天天看點

TensorFlow1.x入門(9)——卷積神經網絡(CNN)系列文章引言知識點示例

系列文章

本教程有同步的github位址

0. 統領篇

1. 計算圖的建立與啟動

2. 變量的定義及其操作

3. Feed與Fetch

4. 線性回歸

5. 建構非線性回歸模型

6. 簡單分類問題

7. Dropout與優化器

8. 手動調整學習率與TensorBoard

9. 卷積神經網絡(CNN)

10. 循環神經網絡(RNN)

11. 模型的儲存與恢複

卷積神經網絡(CNN)

  • 系列文章
  • 引言
  • 知識點
  • 示例

引言

卷積神經網絡(Convolutional Neural Networks, CNN)是深度學習領域内的一個重要的組成建構。CNN現在大量的用于圖像識别領域,但是在自然語言處理和語音識别領域作為特征抽取器有廣泛的應用。

一般情況下,提到卷積神經網絡,它的網絡結構包含卷積層和池化層。卷積層主用用于提取特征,而池化層有最大池化和平均池化,用于過濾特征。

知識點

基于示例中的代碼講解

tf.truncated_normal()

是高斯截斷初始化,随機生成的高斯分布的值,但生成的值不在2個标準差内的會進行丢棄。傳入的參數shape是生成資料的大小,而stddev則是标準差。

tf.nn.conv2d()

是TensorFlow中的二維卷積函數,x為輸入的資料,w為卷積核大大小和通道數。strides的第一位和最後一位為1,剩下的代表卷積核的步長。padding隻有“SAME”和“VLIAD”兩種。

tf.nn.max_pool()

是TensorFlow中的最大池化函數,x為輸入的資料,kszie為池化層的核大小,strides為步長這,padding是模式的選擇,與tf.nn.conv2d()含義相同。

tf.reshape()

是對資料的重構(形狀方面),可以改變資料的shape。

示例

#%% md
# 9-卷積神經網絡(CNN)
#%% md
卷積神經網絡是一類良好的特征提取器,多用于圖像識别領域,現在在自然語言處理領域和語音識别領域也有較為廣泛的運用。
#%% md
導包
#%%
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#%% md
載入資料
#%%
mnist = input_data.read_data_sets("MNIST", one_hot=True)
#%% md
設定batch_size的大小和批次
#%%
batch_size = 100
n_batchs = mnist.train.num_examples // batch_size
#%%
n_batchs
#%% md
設定權重初始化函數

傳入shape,傳回對應shape的參數,服從高斯分布,0均值,0.1方差
#%%
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)
#%% md
設定偏執初始化的函數

傳入shape,傳回對應的0.1的參數
#%%
def biases_vriable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)
#%% md
定義卷積層函數,用于生成一個對應的卷積操作
#%%
def  conv2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
#%% md
定義$2\times 2$的池化層
#%%
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
#%% md
定義兩個placeholder
#%%
x = tf.placeholder(shape=[None, 784], dtype=tf.float32)
y = tf.placeholder(shape=[None, 10], dtype=tf.float32)
#%%
x,y
#%% md
改變x的shape

輸入的為1維資料,由于使用2D卷積,是以要将資料轉為2D的圖像資料
#%%
x_images = tf.reshape(x, shape=[-1, 28, 28, 1])
#%%
x_images
#%% md
搭建卷積層
#%%
w_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = biases_vriable([32])

h_conv1 = tf.nn.relu(conv2d(x_images, w_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

w_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = biases_vriable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#%%
w_conv1, b_conv1
#%%
h_conv1,h_pool1
#%%
w_conv2, b_conv2
#%%
h_conv2,h_pool2
#%% md
搭建全連接配接網絡

同時将池化層的輸出reshape為全聯接的輸入,并輸入到網絡中
#%%
w_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = biases_vriable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, w_fc1.shape[0]])
h_fc1 = tf.nn.tanh(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
#%% md
設定Dropout
#%%
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#%% md
設定輸出層
#%%
w_fc2 = weight_variable([1024, 10])
b_fc2 = biases_vriable([10])

prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)
#%% md
定義損失函數與優化器
#%%
 loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
#%%
train_step = tf.train.AdamOptimizer(0.001).minimize(loss)
#%% md
定義測評結果
#%%
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#%%
init = tf.global_variables_initializer()
#%% md
訓練
#%%
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(100):
        for batch in range(n_batchs):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, {x: batch_xs, y:batch_ys, keep_prob:0.7})
        acc, l = sess.run([accuracy, loss], {x:mnist.test.images, y:mnist.test.labels, keep_prob: 1.0})
        print("Iter: " + str(epoch) + " Accuracy: " + str(acc) + " Loss: "+ str(l) )
#%%


           

繼續閱讀