MNIST手写数字识别---My way of AI 19

手写数字的识别相当于是深度学习的helloworld

首先这是一个流行数据集可以从网络下载,也可以直接import

from tensorflow.examples.tutorials.mnist import input_data

学这个简单的神经网络之前我们首先要知道这个算法用到的衡量误差的策略和优化方法,我们这里的策略比较固定,在分类问题中常用的损失函数就是交叉熵。优化算法就是反向传播的一些常用算法,我们常用梯度下降(tf.train.GradientDescentOptimizer),(AdamOptimizer),(MomentumOptimizer)。在这片文章的demo中我们用梯度下降的方法。

代码流程

  1. 设置占位符,需要注意的是尽管placeholder中数据维度的信息可以根据数据推到得出,但是本数据比较特殊需要我们来设置一下shape。
  2. 初始化权重(weight)和偏置(bias),一般是随机初始化,为了方便也可以做到指定初始化。
  3. y_predict = tf.matmul(x, weight) + bias得出第一个计算结果
  4. 计算交叉熵(误差)
  5. 拿梯度下降去优化

当然就算各种衡量标准和开启可是图tensorbords都是可选项

结果

MNIST手写数字识别---My way of AI 19
训练到最后的时候准确率已经很高了。

MNIST手写数字识别---My way of AI 19MNIST手写数字识别---My way of AI 19
tensorboirds的可视化图。

代码

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


# # input_data.load()
# # print(mnist)
# print(mnist.train.images)  # 获取特征值
# print(mnist.train.images[0])  # 获取第一个样本
# print(mnist.train.next_batch(50))  # 批量获取50个样本


# 单层(全连接层实现手写数字识别)

def full_connnected():
    """
    全连接层神经网络
    :return: None
    """
    # 获取数据
    mnist = input_data.read_data_sets("./data", one_hot=True)
    # 建立占位符,x{None,784}  y_true[None,10]
    with tf.variable_scope("data"):
        x = tf.placeholder(tf.float32, [None, 784])

        y_true = tf.placeholder(tf.int32, [None, 10])

    # 建立一个全连接层的神经网络w[784,10] b[10]
    with tf.variable_scope("fc_model"):
        # 随机初始化权重和偏置
        weight = tf.Variable(tf.random_normal([784, 10], mean=0.0, stddev=1.0), name="w")

        bias = tf.Variable(tf.constant(0.0, shape=[10]))

        # 预测None个样本的输出结果:[none,784]*[784,10]+[10]=[none,10]
        y_predict = tf.matmul(x, weight) + bias

    with tf.variable_scope("soft_max"):
        # 求平均交叉熵损失
        loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))

    # 梯度下降求出损失
    with tf.variable_scope("optimaizer"):
        train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    # 计算准确率
    with tf.variable_scope("acc"):
        equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))

        accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))

    # 收集变量,单个数字收集
    tf.summary.scalar("loss", loss)
    # tf.summary.scalar()

    # 高维度收集
    tf.summary.histogram("weight", weight)
    tf.summary.histogram("bias", bias)

    # 定义一个合并变量的op
    merged = tf.summary.merge_all()

    # 定义一个初始化变量的op
    init_op = tf.global_variables_initializer()

    # 开启会话去训练
    with tf.Session() as sess:
        sess.run(init_op)

        # 建立events文件写入
        filewrite = tf.summary.FileWriter("./data", graph=sess.graph)

        # 迭代步数去训练,更新参数预测

        for i in range(2400):
            # 取出真实存在的特征值和目标值
            mnist_x, mnist_y = mnist.train.next_batch(50)

            # 运行训练
            sess.run(train_op, feed_dict={x: mnist_x, y_true: mnist_y})

            # 写入每步训练的值
            summary = sess.run(merged, feed_dict={x: mnist_x, y_true: mnist_y})
            filewrite.add_summary(summary, i)

            print("训练第%d步,准确率为%f" % (i, sess.run(accuracy, feed_dict={x: mnist_x, y_true: mnist_y})))

    return None


if __name__ == "__main__":
    full_connnected()

github: https://github.com/zhangyuespec/AI

author: [email protected] 欢迎交流