這里使用TensorFlow實現(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ò)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
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)重制造一些隨機噪聲來打破完全對稱,使用截斷的正態(tài)分布,標(biāo)準(zhǔn)差設(shè)為0.1, # 同時因為使用relu,也給偏執(zhí)增加一些小的正值(0.1)用來避免死亡節(jié)點(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是真實的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ù)進行參數(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é)點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ù)測值的索引和真實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 # 每進行一次迭代選擇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)確率進行一次測試 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次之后,測試分類正確率達到了98.6%
step: 999 cost: 0.000048231 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.986
在2000次的時候達到了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ù)集實現(xiàn)示例的詳細(xì)內(nèi)容,更多關(guān)于TensorFlow卷積神經(jīng)網(wǎng)絡(luò)MNIST數(shù)據(jù)集的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/lwplwf/article/details/60876990