TensorFlow學習筆記(5)--實現卷積神經網路(MNIST資料集)

來源:互聯網
上載者:User

這裡使用TensorFlow實現一個簡單的卷積神經網路,使用的是MNIST資料集。網路結構為:資料輸入層–卷積層1–池化層1–卷積層2–池化層2–全串連層1–全串連層2(輸出層),這是一個簡單但非常有代表性的卷積神經網路。

import tensorflow as tfimport numpy as npimport input_datamnist = input_data.read_data_sets('data/', one_hot=True)print("MNIST ready")sess = tf.InteractiveSession()# 定義好初始化函數以便重複使用。給權重製造一些隨機雜訊來打破完全對稱,使用截斷的常態分佈,標準差設為0.1,# 同時因為使用relu,也給偏執增加一些小的正值(0.1)用來避免死亡節點(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') # 參數分別指定了卷積核的尺寸、多少個channel、filter的個數即產生特徵圖的個數# 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的灰階圖,像素個數784n_output = 10  # 是10分類問題# 在設計網路結構前,先定義輸入的placeholder,x是特徵,y是真實的labelx = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_output]) x_image = tf.reshape(x, [-1, 28, 28, 1]) # 對映像做預先處理,將1D的輸入向量轉為2D的圖片結構,即1*784到28*28的結構,-1代表樣本數量不固定,1代表色彩通道數量# 定義第一個卷積層,使用前面寫好的函數進行參數初始化,包括weight和biasW_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個特徵圖轉換為1D向量,隱含節點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) #前向傳播的預測值,print("CNN READY")# 定義損失函數為交叉熵損失函數cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=[1]))# 最佳化器optm = tf.train.AdamOptimizer(0.001).minimize(cost)# 定義評測準確率的操作corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # 對比預測值的索引和真實label的索引是否一樣,一樣返回True,不一樣返回Falseaccuracy = tf.reduce_mean(tf.cast(corr, tf.float32))# 初始化所有參數tf.global_variables_initializer().run()print("FUNCTIONS READY")training_epochs = 1000 # 所有樣本迭代1000次batch_size = 100 # 每進行一次迭代選擇100個樣本display_step = 1for 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次訓練,對準確率進行一次測試        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")

訓練迭代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

相比之前簡單神經網路,CNN的效果明顯較好,這其中主要的效能提升都來自於更優秀的網路設計,即卷積神經網路對映像特徵的提取和抽象能力。依靠卷積核的權值共用,CNN的參數量並沒有爆炸,降低計算量的同時也減輕了過擬合,因此整個模型的效能有較大的提升。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.