TensorFlow卷積神經(jīng)網(wǎng)絡(luò)MNIST數(shù)據(jù)集實(shí)現(xiàn)示例
這里使用TensorFlow實(shí)現(xiàn)一個簡單的卷積神經(jīng)網(wǎng)絡(luò),使用的是MNIST數(shù)據(jù)集。網(wǎng)絡(luò)結(jié)構(gòu)為:數(shù)據(jù)輸入層–卷積層1–池化層1–卷積層2–池化層2–全連接層1–全連接層2(輸出層),這是一個簡單但非常有代表性的卷積神經(jīng)網(wǎng)絡(luò)。
import tensorflow as tf
import numpy as np
import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
print("MNIST ready")
sess = tf.InteractiveSession()
# 定義好初始化函數(shù)以便重復(fù)使用。給權(quán)重制造一些隨機(jī)噪聲來打破完全對稱,使用截斷的正態(tài)分布,標(biāo)準(zhǔn)差設(shè)為0.1,
# 同時因?yàn)槭褂胷elu,也給偏執(zhí)增加一些小的正值(0.1)用來避免死亡節(jié)點(diǎn)(dead neurons)
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):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') # 參數(shù)分別指定了卷積核的尺寸、多少個channel、filter的個數(shù)即產(chǎn)生特征圖的個數(shù)
# 2x2最大池化,即將一個2x2的像素塊降為1x1的像素。最大池化會保留原始像素塊中灰度值最高的那一個像素,即保留最顯著的特征。
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
n_input = 784 # 28*28的灰度圖,像素個數(shù)784
n_output = 10 # 是10分類問題
# 在設(shè)計網(wǎng)絡(luò)結(jié)構(gòu)前,先定義輸入的placeholder,x是特征,y是真實(shí)的label
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
x_image = tf.reshape(x, [-1, 28, 28, 1]) # 對圖像做預(yù)處理,將1D的輸入向量轉(zhuǎn)為2D的圖片結(jié)構(gòu),即1*784到28*28的結(jié)構(gòu),-1代表樣本數(shù)量不固定,1代表顏色通道數(shù)量
# 定義第一個卷積層,使用前面寫好的函數(shù)進(jìn)行參數(shù)初始化,包括weight和bias
W_conv1 = weight_variable([3, 3, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# 定義第二個卷積層
W_conv2 = weight_variable([3, 3, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# fc1,將兩次池化后的7*7共128個特征圖轉(zhuǎn)換為1D向量,隱含節(jié)點(diǎn)1024由自己定義
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
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)
# 為了減輕過擬合,使用Dropout層
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# Dropout層輸出連接一個Softmax層,得到最后的概率輸出
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
pred = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #前向傳播的預(yù)測值,
print("CNN READY")
# 定義損失函數(shù)為交叉熵?fù)p失函數(shù)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=[1]))
# 優(yōu)化器
optm = tf.train.AdamOptimizer(0.001).minimize(cost)
# 定義評測準(zhǔn)確率的操作
corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # 對比預(yù)測值的索引和真實(shí)label的索引是否一樣,一樣返回True,不一樣返回False
accuracy = tf.reduce_mean(tf.cast(corr, tf.float32))
# 初始化所有參數(shù)
tf.global_variables_initializer().run()
print("FUNCTIONS READY")
training_epochs = 1000 # 所有樣本迭代1000次
batch_size = 100 # 每進(jìn)行一次迭代選擇100個樣本
display_step = 1
for i in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
batch = mnist.train.next_batch(batch_size)
optm.run(feed_dict={x:batch[0], y:batch[1], keep_prob:0.7})
avg_cost += sess.run(cost, feed_dict={x:batch[0], y:batch[1], keep_prob:1.0})/total_batch
if i % display_step ==0: # 每10次訓(xùn)練,對準(zhǔn)確率進(jìn)行一次測試
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y:batch[1], keep_prob:1.0})
test_accuracy = accuracy.eval(feed_dict={x:mnist.test.images, y:mnist.test.labels, keep_prob:1.0})
print("step: %d cost: %.9f TRAIN ACCURACY: %.3f TEST ACCURACY: %.3f" % (i, avg_cost, train_accuracy, test_accuracy))
print("DONE")
訓(xùn)練迭代1000次之后,測試分類正確率達(dá)到了98.6%
step: 999 cost: 0.000048231 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.986
在2000次的時候達(dá)到了99.1%
step: 2004 cost: 0.000042901 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.991
相比之前簡單神經(jīng)網(wǎng)絡(luò),CNN的效果明顯較好,這其中主要的性能提升都來自于更優(yōu)秀的網(wǎng)絡(luò)設(shè)計,即卷積神經(jīng)網(wǎng)絡(luò)對圖像特征的提取和抽象能力。依靠卷積核的權(quán)值共享,CNN的參數(shù)量并沒有爆炸,降低計算量的同時也減輕了過擬合,因此整個模型的性能有較大的提升。
以上就是TensorFlow卷積神經(jīng)網(wǎng)絡(luò)MNIST數(shù)據(jù)集實(shí)現(xiàn)示例的詳細(xì)內(nèi)容,更多關(guān)于TensorFlow卷積神經(jīng)網(wǎng)絡(luò)MNIST數(shù)據(jù)集的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)簡單HTML表格解析的方法
這篇文章主要介紹了Python實(shí)現(xiàn)簡單HTML表格解析的方法,涉及Python基于libxml2dom模塊操作html頁面元素的技巧,需要的朋友可以參考下2015-06-06
Matplotlib實(shí)戰(zhàn)之直方圖繪制詳解
直方圖,又稱質(zhì)量分布圖,用于表示數(shù)據(jù)的分布情況,是一種常見的統(tǒng)計圖表,這篇文章主要為大家詳細(xì)介紹了如何使用Matplotlib繪制直方圖,需要的可以參考下2023-08-08
Ubuntu16安裝CUDA(9.1)和cuDNN的實(shí)現(xiàn)步驟(圖文)
本文主要介紹了Ubuntu16安裝CUDA(9.1)和cuDNN,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07
python append、extend與insert的區(qū)別
這篇文章主要介紹了python append、extend與insert的區(qū)別的相關(guān)資料,初學(xué)者對這幾個概念經(jīng)常搞混,這里就幫大家理清楚,需要的朋友可以參考下2016-10-10
Python的Django框架中settings文件的部署建議
這篇文章主要介紹了Python的Django框架中settings文件的部署建議,包括對local_settings的弊病的一些簡單分析,需要的朋友可以參考下2015-05-05

