TensorFlow MNIST手写数字识别(神经网络极简版)

简介: TensorFlow MNIST手写数字识别(神经网络极简版)

MNIST手写数字识别数据集是NIST数据集的一个子集(介绍),常用于深度学习的入门样例。


该数据集包含60000张图片作为训练数据(为验证模型效果,一般从验证数据中划分出一部分作为验证数据,一般为5000),10000张图片作为测试数据。MNIST数据集中每张图片代表0-9中的一个数字,图片大小为28 × 28 ,且数字都位于图片中央。


(1) 加载数据


Tensorflow提供了一个类来处理MNIST数据,这个类会自动下载并转化MNIST数据的格式,将原始数据解析成可直接进行训练和测试的数据格式。代码如下:

mnist = input_data.read_data_sets("datasets/MNIST_data/", one_hot=True)
print("Training data size: ", mnist.train.num_examples)        #55000
print("Validating data size: ", mnist.validation.num_examples) #5000
print("Testing data size: ", mnist.test.num_examples)          #10000


(2)设置参数


learning_rate = 0.0001  # 学习率
num_epochs = 1000       # 迭代次数
BATCH_SIZE = 100        #每轮迭代的训练数据个数


(3)前向传播


定义神经网络,输入层为784 ( 对 应 像 素 28 × 28 ) 784(对应像素28 )784(对应像素28×28),隐藏层为500 ,输出层为10 (对应10 个类别)。代码如下:

(m,n_x) = mnist.train.images.shape #784
n_y = mnist.train.labels.shape[1] #10
n_1 = 500
X = tf.placeholder(tf.float32, shape=(None,n_x), name="X")  #(55000,784)
Y = tf.placeholder(tf.float32, shape=(None,n_y), name="Y")  #(55000,10)
W1 = tf.get_variable("w1",[n_x,n_1],initializer = tf.contrib.layers.xavier_initializer(seed = 1))   #(784,500)
b1 = tf.get_variable("b1",[1,n_1],  initializer = tf.zeros_initializer())                          #(1,500)
W2 = tf.get_variable("w2",[n_1,n_y],initializer = tf.contrib.layers.xavier_initializer(seed = 1))  #(500,10)
b2 = tf.get_variable("b2",[1,n_y],  initializer = tf.zeros_initializer())                          #(1,10)
Z1 = tf.nn.relu(tf.matmul(X,W1) + b1) #(55000,500)
Z2 = tf.matmul(Z1,W2) + b2            #(55000,10)

(4)定义损失函数


使用交叉熵损失函数,代码如下:

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z2, labels = Y))

(5) 优化器


使用Adam优化器,代码如下


optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)


(6)模型训练

with tf.Session() as sess:
    tf.initialize_all_variables().run()
    for i in range(num_epochs):
        x,y = mnist.train.next_batch(BATCH_SIZE)
        sess.run(optimizer,feed_dict={X:x,Y:y})
        if i%500 == 0:
            cost_v = sess.run(cost,feed_dict={X:x,Y:y})
            costs.append(cost_v)
            print(i,cost_v)
   # Calculate the correct accuracy
    correct_prediction = tf.equal(tf.argmax(Z2,1), tf.argmax(Y,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print ("Train Accuracy:", accuracy.eval({X:mnist.train.images, Y: mnist.train.labels})) #Train Accuracy: 0.98807275
    print ("Test Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}))   #Test Accuracy: 0.9756

(7)模型评估


代码如下:

plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()

生成图形如下:

20200523135423757.png

可以看出损失值随迭代轮数增加而减小。


下载完整代码

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("datasets/MNIST_data/", one_hot=True)
learning_rate = 0.0001
num_epochs = 10000
BATCH_SIZE = 100
(m,n_x) = mnist.train.images.shape #784
n_y = mnist.train.labels.shape[1] #10
n_1 = 500
costs = []
tf.set_random_seed(1)        # to keep consistent results
ops.reset_default_graph()    # to be able to rerun the model without overwriting tf variables
X = tf.placeholder(tf.float32, shape=(None,n_x), name="X")  #(55000,784)
Y = tf.placeholder(tf.float32, shape=(None,n_y), name="Y")  #(55000,10)
W1 = tf.get_variable("w1",[n_x,n_1],initializer = tf.contrib.layers.xavier_initializer(seed = 1))   #(784,500)
b1 = tf.get_variable("b1",[1,n_1],  initializer = tf.zeros_initializer())                          #(1,500)
W2 = tf.get_variable("w2",[n_1,n_y],initializer = tf.contrib.layers.xavier_initializer(seed = 1))  #(500,10)
b2 = tf.get_variable("b2",[1,n_y],  initializer = tf.zeros_initializer())                          #(1,10)
Z1 = tf.nn.relu(tf.matmul(X,W1) + b1) #(55000,500)
Z2 = tf.matmul(Z1,W2) + b2            #(55000,10)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z2, labels = Y))
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
with tf.Session() as sess:
    tf.initialize_all_variables().run()
    for i in range(num_epochs):
        x,y = mnist.train.next_batch(BATCH_SIZE)
        sess.run(optimizer,feed_dict={X:x,Y:y})
        if i%500 == 0:
            cost_v = sess.run(cost,feed_dict={X:x,Y:y})
            costs.append(cost_v)
            print(i,cost_v)
   # Calculate the correct accuracy
    correct_prediction = tf.equal(tf.argmax(Z2,1), tf.argmax(Y,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print ("Train Accuracy:", accuracy.eval({X:mnist.train.images, Y: mnist.train.labels})) #Train Accuracy: 0.98807275
    print ("Test Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}))   #Test Accuracy: 0.9756
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()


目录
打赏
0
0
0
1
52
分享
相关文章
猫狗宠物识别系统Python+TensorFlow+人工智能+深度学习+卷积网络算法
宠物识别系统使用Python和TensorFlow搭建卷积神经网络,基于37种常见猫狗数据集训练高精度模型,并保存为h5格式。通过Django框架搭建Web平台,用户上传宠物图片即可识别其名称,提供便捷的宠物识别服务。
367 55
基于Python深度学习的【蘑菇识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
蘑菇识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了9种常见的蘑菇种类数据集【"香菇(Agaricus)", "毒鹅膏菌(Amanita)", "牛肝菌(Boletus)", "网状菌(Cortinarius)", "毒镰孢(Entoloma)", "湿孢菌(Hygrocybe)", "乳菇(Lactarius)", "红菇(Russula)", "松茸(Suillus)"】 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Django框架搭建了一个Web网页平台可视化操作界面,
55 11
基于Python深度学习的【蘑菇识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
动物识别系统Python+卷积神经网络算法+TensorFlow+人工智能+图像识别+计算机毕业设计项目
动物识别系统。本项目以Python作为主要编程语言,并基于TensorFlow搭建ResNet50卷积神经网络算法模型,通过收集4种常见的动物图像数据集(猫、狗、鸡、马)然后进行模型训练,得到一个识别精度较高的模型文件,然后保存为本地格式的H5格式文件。再基于Django开发Web网页端操作界面,实现用户上传一张动物图片,识别其名称。
170 1
动物识别系统Python+卷积神经网络算法+TensorFlow+人工智能+图像识别+计算机毕业设计项目
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
宠物识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了37种常见的猫狗宠物种类数据集【'阿比西尼亚猫(Abyssinian)', '孟加拉猫(Bengal)', '暹罗猫(Birman)', '孟买猫(Bombay)', '英国短毛猫(British Shorthair)', '埃及猫(Egyptian Mau)', '缅因猫(Maine Coon)', '波斯猫(Persian)', '布偶猫(Ragdoll)', '俄罗斯蓝猫(Russian Blue)', '暹罗猫(Siamese)', '斯芬克斯猫(Sphynx)', '美国斗牛犬
221 29
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
垃圾识别分类系统。本系统采用Python作为主要编程语言,通过收集了5种常见的垃圾数据集('塑料', '玻璃', '纸张', '纸板', '金属'),然后基于TensorFlow搭建卷积神经网络算法模型,通过对图像数据集进行多轮迭代训练,最后得到一个识别精度较高的模型文件。然后使用Django搭建Web网页端可视化操作界面,实现用户在网页端上传一张垃圾图片识别其名称。
144 0
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
【车辆车型识别】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+算法模型
车辆车型识别,使用Python作为主要编程语言,通过收集多种车辆车型图像数据集,然后基于TensorFlow搭建卷积网络算法模型,并对数据集进行训练,最后得到一个识别精度较高的模型文件。再基于Django搭建web网页端操作界面,实现用户上传一张车辆图片识别其类型。
152 0
【车辆车型识别】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+算法模型
鸟类识别系统Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+ResNet50算法模型+图像识别
鸟类识别系统。本系统采用Python作为主要开发语言,通过使用加利福利亚大学开源的200种鸟类图像作为数据集。使用TensorFlow搭建ResNet50卷积神经网络算法模型,然后进行模型的迭代训练,得到一个识别精度较高的模型,然后在保存为本地的H5格式文件。在使用Django开发Web网页端操作界面,实现用户上传一张鸟类图像,识别其名称。
165 12
鸟类识别系统Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+ResNet50算法模型+图像识别
交通标志识别系统Python+卷积神经网络算法+深度学习人工智能+TensorFlow模型训练+计算机课设项目+Django网页界面
交通标志识别系统。本系统使用Python作为主要编程语言,在交通标志图像识别功能实现中,基于TensorFlow搭建卷积神经网络算法模型,通过对收集到的58种常见的交通标志图像作为数据集,进行迭代训练最后得到一个识别精度较高的模型文件,然后保存为本地的h5格式文件。再使用Django开发Web网页端操作界面,实现用户上传一张交通标志图片,识别其名称。
225 6
交通标志识别系统Python+卷积神经网络算法+深度学习人工智能+TensorFlow模型训练+计算机课设项目+Django网页界面
基于tensorflow、CNN网络识别花卉的种类(图像识别)
基于tensorflow、CNN网络识别花卉的种类(图像识别)
111 1

热门文章

最新文章