TensorFlow MNIST TensorBoard版本

来源:互联网 发布:矩阵求导链式法则 编辑:程序博客网 时间:2024/05/24 04:25

代码 

import tensorflow as tfimport numpy as npfrom tensorflow.examples.tutorials.mnist import input_datasess = tf.InteractiveSession()#远程下载MNIST数据,建议先下载好并保存在MNIST_data目录下def DownloadData():    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)    #编码格式:one-hot    print(mnist.train.images.shape, mnist.train.labels.shape)           #训练数据55000条    print(mnist.test.images.shape, mnist.test.labels.shape)             #测试数据10000条    print(mnist.validation.images.shape, mnist.validation.labels.shape) #验证数据5000条    return mnistdef Train(mnist):    #Step1 定义算法公式Softmax Regression    x = tf.placeholder(tf.float32, shape=(None, 784))            #构建占位符,代表输入的图像,维度None表示样本的数量可以是任意的,维度784代表特征向量,由图像大小28*28转换而来    weights = tf.Variable(tf.zeros([784, 10]))                    #构建一个变量,代表训练目标weights,初始化为0    biases = tf.Variable(tf.zeros([10]))                        #构建一个变量,代表训练目标biases,初始化为0    y = tf.nn.softmax(tf.matmul(x, weights) + biases)                 #构建了一个softmax的模型:y = softmax(Wx + b),y指样本的预测值    y_ = tf.placeholder(tf.float32, [None, 10])  # 构建占位符,代表样本标签的真实值    tf.summary.histogram("/weights", weights)    #Step2 定义损失函数,选定优化器,并指定优化器优化损失函数    # 定义交叉熵损失函数    cross_entropy = tf.reduce_mean( -tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]) )    tf.summary.scalar('cross_entropy', cross_entropy)    # 使用梯度下降算法(学习率为0.5)来最小化这个交叉熵损失函数    train = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)    merged = tf.summary.merge_all()    writer = tf.summary.FileWriter("output/", sess.graph)    #Step3 训练数据    tf.global_variables_initializer().run()    for i in range(2001):                                                  #迭代次数        batch_x, batch_y = mnist.train.next_batch(100)                   #一个batch的大小为100, 使用一个batch的数据来训练模型        sess.run(train, feed_dict={x: batch_x, y_: batch_y})        #用训练数据替代占位符来执行训练        if (i % 100 == 0):            print("i=%d, 准确率=%g" % (i, Test(mnist, weights, biases)) )            result = sess.run(merged, feed_dict={x: batch_x, y_: batch_y})            writer.add_summary(result, i)    print("准确率=%g" % Test(mnist, weights, biases))# 在测试数据上对准确率进行评测def Test(mnist, weights, biases):    x = tf.placeholder(tf.float32, [None, 784]) #测试数据    y = tf.nn.softmax(tf.matmul(x, weights) + biases) #预测值    y_ = tf.placeholder(tf.float32, [None, 10]) #真实值    # tf.argmax()返回的是某一维度上其数据最大所在的索引值,在这里即代表预测值和真实值    # 判断预测值y和真实值y_中最大数的索引是否一致,y的值为1-10概率    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  # 用平均值来统计测试准确率    return sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})  # 打印测试信息def main():    mnist = DownloadData()    Train(mnist)if __name__ == '__main__':    main()

运行TensorBoard