python 簡單使用MNIST數據集+卷積神經網絡實現手寫數字識別

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data

#1 讀取數據
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

#2 建立模型  使用卷積神經網絡

#2.1 輸入圖像與標籤
x = tf.placeholder("float", shape = [None, 28,28,1])
y_ = tf.placeholder("float", shape = [None, 10]) 

#2.2 搭建卷積神經網絡    卷積+卷積+池化+全連接

#2.2.1 卷積層 
w1 = tf.Variable(tf.truncated_normal([3, 3, 1, 32])) #高寬3*3 單通道 32個filter 
b1 = tf.Variable(tf.zeros([32]))                     #每個filter初始bias爲0
conv1 = tf.nn.conv2d(input=x, filter=w1, strides=[1, 1, 1, 1], padding='SAME') + b1
conv1 = tf.nn.relu(conv1)                            #進行卷積 非線性激活

#2.2.2 卷積層
w2 = tf.Variable(tf.truncated_normal([3, 3, 32, 32])) #高寬3*3 32通道 32個filter 
b2 = tf.Variable(tf.zeros([32]))                      #每個filter初始bias爲0
conv2 = tf.nn.conv2d(input=conv1, filter=w2, strides=[1, 1, 1, 1], padding='SAME') + b2
conv2 = tf.nn.relu(conv2)                             #進行卷積 非線性激活 

#2.2.3 池化
pool = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

#2.2.4 全連接
w = tf.Variable(tf.truncated_normal([14 * 14 * 32, 10], stddev=0.1))
b = tf.Variable(tf.zeros([10]))
pool_reshape = tf.reshape(pool, [-1, 14*14*32])

#2.2.5 輸出
y = tf.matmul(pool_reshape, w) + b

#3 損失函數 優化訓練
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y)
crossEntropyLoss = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer().minimize(crossEntropyLoss)

#4 測試
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

#5 開啓會話
with tf.Session() as sess:
    # 初始化
    sess.run(tf.global_variables_initializer())

    # 訓練
    for i in range(501):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        batch_xs = batch_xs.reshape([100,28,28,1])
        sess.run(optimizer, feed_dict={x: batch_xs, y_: batch_ys})
        
        # 測試模型
        #if i%100 == 0:
            #result = sess.run(accuracy, feed_dict={x: mnist.test.images.reshape([10000,28,28,1]), y_: mnist.test.labels}) * 100
            #print(result)
    # 測試模型
    sum = 0;
    for i in range(10000):
        sum += sess.run(accuracy, feed_dict={x: mnist.test.images[i].reshape([1,28,28,1]), y_: mnist.test.labels[i].reshape([1,10])})
    print(sum)
    print(sum/10000)

 結果:       

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章