mnist手寫體識別

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# import os


def mnist_recognition():
    """
    使用全連接進行手寫體識別
    :return:
    """
    # 1、準備數據
    #    兩種數據讀取方式:
    #   (1)、QueueRunner
    #   (2)、Feeding
    mnist = input_data.read_data_sets(r"E:\GameDownload\dataset_mnist", one_hot=True)
    x_train = tf.placeholder(dtype=tf.float32, shape=[None, 784])
    y_true = tf.placeholder(dtype=tf.float32, shape=[None, 10])
    # 2、構建全連接模型(注意模型參數應用變量存儲)
    Weights = tf.Variable(initial_value=tf.random.normal(shape=[784, 10]))
    bias = tf.Variable(initial_value=tf.random.normal(shape=[10]))
    y_predict = tf.matmul(x_train, Weights) + bias
    # print(y_predict)
    # 3、構造損失函數(用softmax表示的交叉熵)
    error = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))
    # 4、優化損失(使用梯度下降方法)
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(error)
    # 5、計算準確率,對y_predict使用argmax可以找出其一行中最大值所在的列
    #    由於使用的是one-hot編碼,所以預測值與真實值在編碼內的位置相同時爲true,否則爲false
    #    之後將bool值轉爲浮點數後求均值,即爲一個batch內true的機率
    equal_list = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_true, 1))
    accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
    init = tf.global_variables_initializer()
    with tf.compat.v1.Session() as sess:
        sess.run(init)
        image, label = mnist.train.next_batch(100)
        # print(x_train)

        for i in range(1000):
            loss, _, y_predict_val, accuracy_val = sess.run([error, optimizer, y_predict, accuracy],
                                                            feed_dict={y_true: label, x_train: image})
            # print("y_predict:\n", sess.run(y_predict, feed_dict={y_true: label, x_train: image}))
            # print("第%d次迭代後:損失爲:%f, 準確率爲%f" % (i + 1, loss, accuracy_val))

        # 6、得到模型之後在測試集中進行驗證
        count = 0.0
        for i in range(100):
            x_test, y_test = mnist.test.next_batch(1)
            test_predict = tf.argmax(sess.run(y_predict, feed_dict={x_train: x_test, y_true: y_test}), 1).eval()
            test_true = tf.argmax(y_test, 1).eval()
            if test_true == test_predict:
                count += 1
            print("第%d次測試的預測值爲:%d, 真實值爲:%d" % (i+1, test_predict, test_true))
            # print(test_true)
        print("在測試集上模型準確率爲:%f" % (count / 100))
    return None


if __name__ == "__main__":
    # file_name_list = os.listdir(r"E:\GameDownload\dataset_mnist")
    # # print(file_name_list)
    # file_list = [os.path.join(r"E:\GameDownload\dataset_mnist", file_name)
    #               for file_name in file_name_list if file_name[-4:] == "byte"]
    # # print(file_queue)
    mnist_recognition()

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