TensorFlow MNIST TensorBoard版本

代码 

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

sess = 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 mnist

def 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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值