基于TensorFlow的CNN(Convolutional Neural Network)模型通過對MNIST資料集訓練,來實作手寫數字識别
導入TensorFlow子產品
import tensorflow as tf
導入imput_data用于下載下傳和安裝MNIST資料集
from tensorflow.examples.tutorials.mnist import input_data
讀取資料集相關内容,如果已下載下傳好,直接寫入目錄
建立兩個占位符,x為輸入網絡的圖像,y_為輸入網絡的圖像類别
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
初始化權重函數
def weight_variable(shape):
#輸出服從截尾正态分布的随機值,标準差為0.1
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
初始化偏執函數
def bias_variable(shape):
#輸出一個常量0.1
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
建立卷積函數
def conv2d(x, W):
#x為輸入的張量,W為卷積核,padding填充(same考慮邊緣,并填充為0,valid則不考慮填充)
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME")
建立池化函數
def max_pool_2x2(x):
#ksize表示pool視窗大小為2x2,也就是高2,寬2
#strides,表示在height和width次元上的步長都為2
return tf.nn.max_pool(x, ksize=[1,2,2,1],strides=[1,2,2,1], padding="SAME")
開始第1層卷積(卷積核為5*5),并池化
#初始化權重W為[5,5,1,32]的張量,表示卷積核大小為5*5,1表示圖像通道數,6表示卷積核個數即輸出6個特征圖
W_conv1 = weight_variable([5,5,1,6])
#初始化偏執b為[6],即輸出大小
b_conv1 = bias_variable([6])
#把輸入x(二維張量,shape為[batch, 784])變成4d的x_image,x_image的shape應該是[batch,28,28,1]
#-1表示自動推測這個次元的size
#将x變成28*28*(1深度)的張量,并且自動推算個數
x_image = tf.reshape(x, [-1,28,28,1])
#把x_image和權重進行卷積,加上偏置項,然後應用ReLU激活函數tf.nn.relu(小于0輸出0,大于0不變),最後進行max_pooling(最大化池化),h_pool1的輸出即為第一層網絡輸出,池化後shape為[batch,14,14,6]
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
第2層卷積
#卷積核大小依然是5*5,通道數為6,卷積核個數為16
W_conv2 = weight_variable([5,5,6,16])
b_conv2 = weight_variable([16])
#h_pool2即為第二層網絡輸出,shape為[batch,7,7,16]
#卷積
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
#2*2池化
h_pool2 = max_pool_2x2(h_conv2)
第3層, 全連接配接層
#這層是擁有1024個神經元的全連接配接層
#W的第1維size為7*7*16,7*7是h_pool2輸出的size,16是第2層輸出神經元個數
W_fc1 = weight_variable([7*7*16, 120])
b_fc1 = bias_variable([120])
#計算前需要把第2層的輸出reshape成[batch, 7*7*16]的張量
#tf.matmul矩陣相乘
#tf.nn.relu将大于0的保持不變,小于0的數置為0。
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*16])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
Dropout層
#為了減少過拟合,在輸出層前加入dropout
#防止或減輕過拟合(為了得到一緻假設而使假設變得過度嚴格)而使用的函數
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
輸出層,第二個全連接配接層
#添加一個softmax層,使用softmax将網絡輸出值換成了機率
W_fc2 = weight_variable([120, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
預測值和真實值之間的交叉墒
#tf.log計數自然對數
#tf.reduce_sum求沿着某一次元的和
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
使用ADAM優化器來做梯度下降。學習率為0.0001
評估模型
#tf.argmax 按照後面值,axis=0時比較每一列的元素,将每一列最大元素所在的索引記錄下來,最後輸出每一列最大元素所在的索引數組。axis=1時比較每一行的元素。
#tf.equal 判斷兩個值是否相等,即判斷預測與正确值是否相等
correct_predict = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
計算正确率
#因為tf.equal傳回的是布爾值,使用tf.cast把布爾值轉換成浮點數
#然後用tf.reduce_mean求平均值
accuracy = tf.reduce_mean(tf.cast(correct_predict, "float"))
執行個體化一個saver對象
#tf.train.Saver() 儲存和加載模型
saver = tf.train.Saver()
開始訓練函數
def cnn_train():
# 建立一個互動式Session
sess = tf.InteractiveSession()
#tf.initialize_all_variables()初始化變量
sess.run(tf.initialize_all_variables())
#循環20000次
for i in range(20000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
#每100次輸出一次日志
train_accuracy = accuracy.eval(feed_dict={
x:batch[0], y_:batch[1], keep_prob:1.0})
print ("step %d, training accuracy %g" % (i, train_accuracy))
#儲存模型
saver.save(sess, './model')
train_step.run(feed_dict={x:batch[0], y_:batch[1], keep_prob:0.5})
預測函數
def predict():
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(tf.global_variables())
saver.restore(sess, 'model')
print( "test accuracy %g" % accuracy.eval(feed_dict={
x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}))
調用主函數
cnn_train()
predict()