MINIST手寫數字識別


1、配置環境:tensorflow+matplotlib

添加matplotlib庫:https://blog.csdn.net/jiaoyangwm/article/details/79252845

2、下載數據:

http://yann.lecun.com/exdb/mnist/

3、主要步驟:

  1)載入數據,解析文件

  2)構建CNN網絡    

    (1)傳統LeNet5包含輸入層、卷積層CONV5-32、池化層pool2、卷積層CONV5-64、池化層pool2、全連接層fc1、輸出層fc。

      改進的LeNet5神經網絡激活函數采用ReLU激活函數,添加dropout層防止過擬合,輸出層為softmax分類層,

INPUT: [28x28x1] weights: 0 CONV5-32: [28x28x32] weights: (5*5*1+1)*32 POOL2: [14x14x32] weights: 2*2*1 CONV5-64: [14x14x64] weights: (5*5*32+1)*64 POOL2: [7x7x64] weights: 2*2*1 FC: [1x1x1024] weights: (7*7*64+1)*1024 FC: [1x1x10] weights: (1*1*512+1)*10

    (2)

    (3)

  3)構建loss function

    softmax損失函數

  4)配置尋優器

    梯度下降法、Adam優化器、動量優化器、Adagrad優化器、FTRL優化器、RMSProp優化器、

  5)訓練、測試

  6)tensorboard可視化

4、詳細解釋

http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html

5、具體實現

多層神經網絡實現MINIST手寫數字識別:

import input_data   #input_data為下載的腳本文件,網址見最后 import tensorflow as tf

mnist = input_data.read_data_sets('F:/PycharmProjects/untitled2/tensorflow/MINIST_data', one_hot=True) #下載的MNIST數據集存儲路徑

x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])

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')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

x_image = tf.reshape(x,[-1,28,28,1])

h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5, 5, 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)

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)

keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

saver = tf.train.Saver() #定義saver

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(2000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            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))
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    saver.save(sess, 'F:/PycharmProjects/untitled2/tensorflow/MINIST_data/model.ckpt') #模型儲存位置

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

 

  運行結果:

    

    

  CNN模型文件:

    

 

 

 

 

 

 

 講一下入過的坑: 

第一個坑: 

  報錯:ImportError: No module named examples.tutorials.mnist.input_data

  這就需要從TensorFlow的官網上下載input_data.py,這個國內可拷貝的鏈接是:http://blog.csdn.net/fdbptha/article/details/51265430。
第二個坑:(安裝tf2.0的后果,變化太大不會使,只能重新安裝低版的tf)

  報錯:AttributeError: module 'tensorflow' has no attribute 'placeholder'

  替換 import tensorflow as tf

  為:import tensorflow.compat.v1 as tf

  報錯:RuntimeError: tf.placeholder() is not compatible with eager execution.

重裝tf1.15版本后可以正常運行了,感動到淚奔T_T

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM