【深度學習】Tensorflow——CNN 卷積神經網路 1
轉自https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-04-CNN2/
這一次我們會說道 CNN 程式碼中怎麼定義 Convolutional 的層和怎樣進行 pooling.
基於上一次卷積神經網路的介紹,我們在程式碼中實現一個基於MNIST資料集的例子
目錄
定義卷積層的 weight bias
首先我們匯入
import tensorflow as tf
採用的資料集依然是tensorflow
mnist
資料集
我們需要先匯入它
python from tensorflow.examples.tutorials.mnist import input_data
本次課程程式碼用到的資料集就是來自於它
mnist=input_data.read_data_sets('MNIST_data',one_hot=true)
接著呢,我們定義Weight
變數,輸入shape
,返回變數的引數。其中我們使用tf.truncated_normal產生隨機變數來進行初始化:
def weight_variable(shape): inital=tf.truncted_normal(shape,stddev=0.1) return tf.Variable(initial)
同樣的定義biase
變數,輸入shape
,返回變數的一些引數。其中我們使用tf.constant
常量函式來進行初始化:
def bias_variable(shape):
initial=tf.constant(0.1,shape=shape)
return tf.Variable(initial)
定義卷積,tf.nn.conv2d
函式是tensoflow
裡面的二維的卷積函式,x
是圖片的所有引數,W
是此卷積層的權重,然後定義步長strides=[1,1,1,1]
值,strides[0]
和strides[3]
的兩個1是預設值,中間兩個1代表padding時在x方向運動一步,y方向運動一步,padding採用的方式是SAME
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
定義 pooling
接著定義池化pooling
,為了得到更多的圖片資訊,padding時我們選的是一次一步,也就是strides[1]=strides[2]=1
,這樣得到的圖片尺寸沒有變化,而我們希望壓縮一下圖片也就是引數能少一些從而減小系統的複雜度,因此我們採用pooling
來稀疏化引數,也就是卷積神經網路中所謂的下采樣層。pooling
有兩種,一種是最大值池化,一種是平均值池化,本例採用的是最大值池化tf.max_pool()
。池化的核函式大小為2x2,因此ksize=[1,2,2,1]
,步長為2,因此strides=[1,2,2,1]
:
def max_poo_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1])
完整程式碼
# 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]) # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
## conv1 layer ##
## conv2 layer ##
## func1 layer ##
## func2 layer ##
# 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]))
好啦,如果你對本節課內容已經瞭解,下一次課【深度學習】Tensorflow——CNN 卷積神經網路 2我們將構建卷積神經網路的架構~