tensorflow学习笔记 -- 简单神经网络实现

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


def network():
    # 获取真实数据
    real_data = input_data.read_data_sets("./data/mnist/input_data", one_hot=True)

    # 1. 建立数据的占位符
    with tf.variable_scope("data"):
        x = tf.placeholder(tf.float32, [None, 782])

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

    # 2. 建立一个全连接层的神经网络
    with tf.variable_scope("model"):
        # 创建随机权重变量
        weight = tf.Variable(tf.random_normal(shape=[782, 10], mean=0.0, stddev=1.0), name="weights")
        # 创建随机偏置变量
        bias = tf.Variable(tf.constant(0.0, shape=[10]))
        # 预测样本输出结果, [None, 782] * [782, 10] + [10]
        y_predict = tf.matmul(x, weight) + bias

    # 3. 求所有样本的损失然后取平均值
    with tf.variable_scope("loss"):
        # 求平均交叉熵损失
        loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict), name="losses")

    # 4. 梯度下降优化损失
    with tf.variable_scope("optimizer"):
        train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    # 5. 计算准确率
    with tf.variable_scope("accuracy"):
        # 判断y_true和y_predict中最大的那个值的下标是否一致,一致则正确
        equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))

        # equal_list中有None个样本,样式为[1, 0, 0, 1, 0, 1, 1, ....] 0为错误,1为正确
        # 对equal_list中的值求平均值就是准确率
        accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))

    # 收集变量
    # 低纬度变量
    tf.summary.scalar("loss", loss)
    tf.summary.scalar("accuracy", accuracy)
    # 高纬度变量
    tf.summary.histogram("weight", weight)
    tf.summary.histogram("bias", bias)

    # 定义初始化op
    init_op = tf.global_variables_initializer()

    # 定义合并变量op
    merge = tf.summary.merge_all()

    # 开启会话
    with tf.Session() as sess:
        # 初始化变量
        sess.run(init_op)

        # 创建events文件
        file_writer = tf.summary.FileWriter("./summary/test/", graph=sess.graph)

        # 迭代步数训练
        for i in range(2000):
            # 取出真实存在的特征值和目标值
            real_data_x, real_data_y = real_data.train.next_batch(50)

            # 运行train_op训练,将真实值放入占位符中
            sess.run(train_op, feed_dict={x: real_data_x, y_true: real_data_y})

            # 写入每步训练的值
            summary = sess.run(merge, feed_dict={x: real_data_x, y_true: real_data_y})
            file_writer.add_summary(summary, i)

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

    return None


if __name__ == "__main__":
    network()

 

你可能感兴趣的:(人工智能,学习笔记)