【深度學習】Tensorflow——CNN 卷積神經網路 2
轉自https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-05-CNN3/
目錄
這一次我們一層層的加上了不同的 layer. 分別是:
- convolutional layer1 + max pooling;
- convolutional layer2 + max pooling;
- fully connected layer1 + dropout;
- fully connected layer2 to prediction.
我們利用上節課【深度學習】Tensorflow——CNN 卷積神經網路 1定義好的函式來構建我們的網路
圖片處理
首先呢,我們定義一下輸入的placeholder
xs=tf.placeholder(tf.float32,[None,784])
ys=tf.placeholder(tf.float32,[None,10])
我們還定義了dropout
的placeholder
,它是解決過擬合的有效手段
keep_prob=tf.placeholder(tf.float32)
接著呢,我們需要處理我們的xs
,把xs
的形狀變成[-1,28,28,1]
,-1代表先不考慮輸入的圖片例子多少這個維度,後面的1是channel的數量,因為我們輸入的圖片是黑白的,因此channel是1,例如如果是RGB影象,那麼channel就是3。
x_image=tf.reshape(xs,[-1,28,28,1])
建立卷積層
接著我們定義第一層卷積,先定義本層的Weight
,本層我們的卷積核patch的大小是5x5,因為黑白圖片channel是1所以輸入是1,輸出是32個featuremap
W_conv1=weight_variable([5,5,1,32])
接著定義bias
,它的大小是32個長度,因此我們傳入它的shape
為[32]
b_conv1=bias_variable([32])
定義好了Weight
和bias
,我們就可以定義卷積神經網路的第一個卷積層h_conv1=conv2d(x_image,W_conv1)+b_conv1
h_conv1
進行非線性處理,也就是啟用函式來處理嘍,這裡我們用的是tf.nn.relu
(修正線性單元)來處理,要注意的是,因為採用了SAME
的padding方式,輸出圖片的大小沒有變化依然是28x28,只是厚度變厚了,因此現在的輸出大小就變成了28x28x32
h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
最後我們再進行pooling
的處理就ok啦,經過pooling
的處理,輸出大小就變為了14x14x32
h_pool=max_pool_2x2(h_conv1)
接著呢,同樣的形式我們定義第二層卷積,本層我們的輸入就是上一層的輸出,本層我們的卷積核patch的大小是5x5,有32個featuremap所以輸入就是32,輸出呢我們定為64
W_conv2=weight_variable([5,5,32,64])
b_conv2=bias_variable([64])
接著我們就可以定義卷積神經網路的第二個卷積層,這時的輸出的大小就是14x14x64
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
最後也是一個pooling處理,輸出大小為7x7x64
h_pool2=max_pool_2x2(h_conv2)
建立全連線層
好的,接下來我們定義我們的 fully connected layer,
進入全連線層時, 我們通過tf.reshape()
將h_pool2
的輸出值從一個三維的變為一維的資料, -1表示先不考慮輸入圖片例子維度, 將上一個輸出結果展平.
#[n_samples,7,7,64]->>[n_samples,7*7*64]
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])
此時weight_variable
的shape
輸入就是第二個卷積層展平了的輸出大小: 7x7x64, 後面的輸出size我們繼續擴大,定為1024
W_fc1=weight_variable([7*7*64,1024])
b_fc1=bias_variable([1024])
然後將展平後的h_pool2_flat
與本層的W_fc1
相乘(注意這個時候不是卷積了)
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
如果我們考慮過擬合問題,可以加一個dropout的處理
h_fc1_drop=tf.nn.dropout(h_fc1,keep_drop)
接下來我們就可以進行最後一層的構建了,好激動啊, 輸入是1024,最後的輸出是10個 (因為mnist資料集就是[0-9]十個類),prediction就是我們最後的預測值
W_fc2=weight_variable([1024,10]) b_fc2=bias_variable([10])
然後呢我們用softmax分類器(多分類,輸出是各個類的概率),對我們的輸出進行分類
prediction=tf.nn.softmax(tf.matmul(h_fc1_dropt,W_fc2) + b_fc2)
選優化方法
為了訓練我們的模型,我們首先需要定義一個指標來評估這個模型是好的。其實,在機器學習,我們通常定義指標來表示一個模型是壞的,這個指標稱為成本(cost)或損失(loss),然後儘量最小化這個指標。但是,這兩種方式是相同的。
一個非常常見的,非常漂亮的成本函式是“交叉熵”(cross-entropy)。交叉熵產生於資訊理論裡面的資訊壓縮編碼技術,但是它後來演變成為從博弈論到機器學習等其他領域裡的重要技術手段。它的定義如下:
y 是我們預測的概率分佈, y' 是實際的分佈(我們輸入的one-hot vector)。比較粗糙的理解是,交叉熵是用來衡量我們的預測用於描述真相的低效性。更詳細的關於交叉熵的解釋超出本教程的範疇,但是你很有必要好好理解它。
接著呢我們利用交叉熵損失函式來定義我們的cost function
cross_entropy=tf.reduce_mean(
-tf.reduce_sum(ys*tf.log(prediction),
reduction_indices=[1]))
我們用tf.train.AdamOptimizer()
作為我們的優化器進行優化,使我們的cross_entropy
最小
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
接著呢就是和之前視訊講的一樣嘍 定義Session
sess=tf.Session()
初始化變數
# tf.initialize_all_variables() 這種寫法馬上就要被廢棄
# 替換成下面的寫法:
sess.run(tf.global_variables_initializer())
好啦接著就是訓練資料啦,我們假定訓練1000
步,每50
步輸出一下準確率, 注意sess.run()
時記得要用feed_dict
給我們的眾多 placeholder
喂資料哦.
完整程式碼
# View more python tutorial on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
return result
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
# stride [1, x_movement, y_movement, 1]
# Must have strides[0] = strides[3] = 1
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
# stride [1, x_movement, y_movement, 1]
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784])/255. # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
# print(x_image.shape) # [n_samples, 28,28,1]
## conv1 layer ##
W_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
h_pool1 = max_pool_2x2(h_conv1) # output size 14x14x32
## conv2 layer ##
W_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64
h_pool2 = max_pool_2x2(h_conv2) # output size 7x7x64
## fc1 layer ##
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
# [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]
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)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
## fc2 layer ##
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1])) # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
sess = tf.Session()
# important step
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images[:1000], mnist.test.labels[:1000]))
以上呢就是一個簡單的卷積神經網路的例子程式碼。