MNIST(Mixed National Institute of Standards and Technology)http://yann.lecun.com/exdb/mnist/ ,入门级计算机视觉数据集,美国中学生手写数字。训练集6万张图片,测试集1万张图片。数字经过预处理、格式化,大小调整并居中,图片尺寸固定28x28。数据集小,训练速度快,收敛效果好。

MNIST数据集,NIST数据集子集。4个文件。train-label-idx1-ubyte.gz 训练集标记文件(28881字节),train-images-idx3-ubyte.gz 训练集图片文件(9912422字节),t10k-labels-idx1-ubyte.gz,测试集标记文件(4542字节),t10k-images-idx3-ubyte.gz 测试集图片文件(1648877字节)。测试集,前5000个样例取自原始NIST训练集,后5000个取自原始NIST测试集。

训练集标记文件 train-labels-idx1-ubyt格式:offset、type、value、description。magic number(MSB first)、number of items、label。
MSB(most significant bit,最高有效位),二进制,MSB最高加权位。MSB位于二进制最左侧,MSB first 最高有效位在前。 magic number 写入ELF格式(Executable and Linkable Format)的ELF头文件常量,检查和自己设定是否一致判断文件是否损坏。

训练集图片文件 train-images-idx3-ubyte格式:magic number、number of images、number of rows、number of columns、pixel。
pixel(像素)取值范围0-255,0-255代表背景色(白色),255代表前景色(黑色)。

测试集标记文件 t10k-labels-idx1-ubyte 格式:magic number(MSB first)、number of items、label。

测试集图片文件 t10k-images-idx3-ubyte格式:magic number、number of images、number of rows、number of columns、pixel。

tensor flow-1.1.0/tensorflow/examples/tutorials/mnist。mnist_softmax.py 回归训练,full_connected_feed.py Feed数据方式训练,mnist_with_summaries.py 卷积神经网络(CNN) 训练过程可视化,mnist_softmax_xla.py XLA框架。

MNIST分类问题。

Softmax回归解决两种以上分类。Logistic回归模型在分类问题推广。tensorflow-1.1.0/tensorflow/examples/tutorials/mnist/mnist_softmax.py。

加载数据。导入input_data.py文件, tensorflow.contrib.learn.read_data_sets加载数据。FLAGS.data_dir MNIST路径,可自定义。one_hot标记,长度为n数组,只有一个元素是1.0,其他元素是0.0。输出层softmax,输出概率分布,要求输入标记概率分布形式,以更计算交叉熵。

构建回归模型。输入原始真实值(group truth),计算softmax函数拟合预测值,定义损失函数和优化器。用梯度下降算法以0.5学习率最小化交叉熵。tf.train.GradientDescentOptimizer。

训练模型。初始化创建变量,会话启动模型。模型循环训练1000次,每次循环随机抓取训练数据100个数据点,替换占位符。随机训练(stochastic training),SGD方法梯度下降,每次从训练数据随机抓取小部分数据梯度下降训练。BGD每次对所有训练数据计算。SGD学习数据集总体特征,加速训练过程。

评估模型。tf.argmax(y,1)返回模型对任一输入x预测标记值,tf.argmax(y_,1) 正确标记值。tf.equal检测预测值和真实值是否匹配,预测布尔值转化浮点数,取平均值。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
FLAGS = None
def main(_):
# Import data 加载数据
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
# Create the model 定义回归模型
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b #预测值
# Define loss and optimizer 定义损失函数和优化器
y_ = tf.placeholder(tf.float32, [None, 10]) # 输入真实值占位符
# tf.nn.softmax_cross_entropy_with_logits计算预测值y与真实值y_差值,取平均值
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# SGD优化器
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# InteractiveSession()创建交互式上下文TensorFlow会话,交互式会话会成为默认会话,可以运行操作(OP)方法(tf.Tensor.eval、tf.Operation.run)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
# Train 训练模型
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# Test trained model 评估训练模型
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 计算模型测试集准确率
print(sess.run(accuracy, feed_dict={x: mnist.test.images,
y_: mnist.test.labels}))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

训练过程可视化。tensorflow-1.1.0/tensorflow/examples/tutorials/mnist/mnist_summaries.py 。
TensorBoard可视化,训练过程,记录结构化数据,支行本地服务器,监听6006端口,浏览器请求页面,分析记录数据,绘制统计图表,展示计算图。
运行脚本:python mnist_with_summaries.py。
训练过程数据存储在/tmp/tensorflow/mnist目录,可命令行参数--log_dir指定。运行tree命令,ipnut_data # 存放训练数据,logs # 训练结果日志,train # 训练集结果日志。运行tensorboard命令,打开浏览器,查看训练可视化结果,logdir参数标明日志文件存储路径,命令 tensorboard --logdir=/tmp/tensorflow/mnist/logs/mnist_with_summaries 。创建摘要文件写入符(FileWriter)指定。

# sess.graph 图定义,图可视化
file_writer = tf.summary.FileWriter('/tmp/tensorflow/mnist/logs/mnist_with_summaries', sess.graph)

浏览器打开服务地址,进入可视化操作界面。

可视化实现。

给一个张量添加多个摘要描述函数variable_summaries。SCALARS面板显示每层均值、标准差、最大值、最小值。
构建网络模型,weights、biases调用variable_summaries,每层采用tf.summary.histogram绘制张量激活函数前后变化。HISTOGRAMS面板显示。
绘制准确率、交叉熵,SCALARS面板显示。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
FLAGS = None
def train():
# Import data
mnist = input_data.read_data_sets(FLAGS.data_dir,
one_hot=True,
fake_data=FLAGS.fake_data)
sess = tf.InteractiveSession()
# Create a multilayer model.
# Input placeholders
with tf.name_scope('input'):
x = tf.placeholder(tf.float32, [None, 784], name='x-input')
y_ = tf.placeholder(tf.float32, [None, 10], name='y-input')
with tf.name_scope('input_reshape'):
image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
tf.summary.image('input', image_shaped_input, 10)
# We can't initialize these variables to 0 - the network will get stuck.
def weight_variable(shape):
"""Create a weight variable with appropriate initialization."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
"""Create a bias variable with appropriate initialization."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
"""对一个张量添加多个摘要描述"""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean) # 均值
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev) # 标准差
tf.summary.scalar('max', tf.reduce_max(var)) # 最大值
tf.summary.scalar('min', tf.reduce_min(var)) # 最小值
tf.summary.histogram('histogram', var)
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
# Adding a name scope ensures logical grouping of the layers in the graph.
# 确保计算图中各层分组,每层添加name_scope
with tf.name_scope(layer_name):
# This Variable will hold the state of the weights for the layer
with tf.name_scope('weights'):
weights = weight_variable([input_dim, output_dim])
variable_summaries(weights)
with tf.name_scope('biases'):
biases = bias_variable([output_dim])
variable_summaries(biases)
with tf.name_scope('Wx_plus_b'):
preactivate = tf.matmul(input_tensor, weights) + biases
tf.summary.histogram('pre_activations', preactivate) # 激活前直方图
activations = act(preactivate, name='activation')
tf.summary.histogram('activations', activations) # 激活后直方图
return activations
hidden1 = nn_layer(x, 784, 500, 'layer1')
with tf.name_scope('dropout'):
keep_prob = tf.placeholder(tf.float32)
tf.summary.scalar('dropout_keep_probability', keep_prob)
dropped = tf.nn.dropout(hidden1, keep_prob)
# Do not apply softmax activation yet, see below.
y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)
with tf.name_scope('cross_entropy'):
diff = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)
with tf.name_scope('total'):
cross_entropy = tf.reduce_mean(diff)
tf.summary.scalar('cross_entropy', cross_entropy) # 交叉熵
with tf.name_scope('train'):
train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(
cross_entropy)
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
with tf.name_scope('accuracy'):
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', accuracy) # 准确率
# Merge all the summaries and write them out to
# /tmp/tensorflow/mnist/logs/mnist_with_summaries (by default)
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph)
test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/test')
tf.global_variables_initializer().run()
def feed_dict(train):
"""Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""
if train or FLAGS.fake_data:
xs, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)
k = FLAGS.dropout
else:
xs, ys = mnist.test.images, mnist.test.labels
k = 1.0
return {x: xs, y_: ys, keep_prob: k}
for i in range(FLAGS.max_steps):
if i % 10 == 0: # Record summaries and test-set accuracy
summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
test_writer.add_summary(summary, i)
print('Accuracy at step %s: %s' % (i, acc))
else: # Record train set summaries, and train
if i % 100 == 99: # Record execution stats
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary, _ = sess.run([merged, train_step],
feed_dict=feed_dict(True),
options=run_options,
run_metadata=run_metadata)
train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
train_writer.add_summary(summary, i)
print('Adding run metadata for', i)
else: # Record a summary
summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
train_writer.add_summary(summary, i)
train_writer.close()
test_writer.close()
def main(_):
if tf.gfile.Exists(FLAGS.log_dir):
tf.gfile.DeleteRecursively(FLAGS.log_dir)
tf.gfile.MakeDirs(FLAGS.log_dir)
train()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--fake_data', nargs='?', const=True, type=bool,
default=False,
help='If true, uses fake data for unit testing.')
parser.add_argument('--max_steps', type=int, default=1000,
help='Number of steps to run trainer.')
parser.add_argument('--learning_rate', type=float, default=0.001,
help='Initial learning rate')
parser.add_argument('--dropout', type=float, default=0.9,
help='Keep probability for training dropout.')
parser.add_argument(
'--data_dir',
type=str,
default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),
'tensorflow/mnist/input_data'),
help='Directory for storing input data')
parser.add_argument(
'--log_dir',
type=str,
default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),
'tensorflow/mnist/logs/mnist_with_summaries'),
help='Summaries log directory')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

参考资料:
《TensorFlow技术解析与实战》

欢迎推荐上海机器学习工作机会,我的微信:qingxingfengzi

学习笔记TF056:TensorFlow MNIST,数据集、分类、可视化的更多相关文章

  1. 学习笔记TF057:TensorFlow MNIST,卷积神经网络、循环神经网络、无监督学习

    MNIST 卷积神经网络.https://github.com/nlintz/TensorFlow-Tutorials/blob/master/05_convolutional_net.py .Ten ...

  2. tensorflow学习笔记——使用TensorFlow操作MNIST数据(1)

    续集请点击我:tensorflow学习笔记——使用TensorFlow操作MNIST数据(2) 本节开始学习使用tensorflow教程,当然从最简单的MNIST开始.这怎么说呢,就好比编程入门有He ...

  3. tensorflow学习笔记——使用TensorFlow操作MNIST数据(2)

    tensorflow学习笔记——使用TensorFlow操作MNIST数据(1) 一:神经网络知识点整理 1.1,多层:使用多层权重,例如多层全连接方式 以下定义了三个隐藏层的全连接方式的神经网络样例 ...

  4. 机器学习与Tensorflow(3)—— 机器学习及MNIST数据集分类优化

    一.二次代价函数 1. 形式: 其中,C为代价函数,X表示样本,Y表示实际值,a表示输出值,n为样本总数 2. 利用梯度下降法调整权值参数大小,推导过程如下图所示: 根据结果可得,权重w和偏置b的梯度 ...

  5. 单向LSTM笔记, LSTM做minist数据集分类

    单向LSTM笔记, LSTM做minist数据集分类 先介绍下torch.nn.LSTM()这个API 1.input_size: 每一个时步(time_step)输入到lstm单元的维度.(实际输入 ...

  6. UFLDL深度学习笔记 (四)用于分类的深度网络

    UFLDL深度学习笔记 (四)用于分类的深度网络 1. 主要思路 本文要讨论的"UFLDL 建立分类用深度网络"基本原理基于前2节的softmax回归和 无监督特征学习,区别在于使 ...

  7. ensorflow学习笔记四:mnist实例--用简单的神经网络来训练和测试

    http://www.cnblogs.com/denny402/p/5852983.html ensorflow学习笔记四:mnist实例--用简单的神经网络来训练和测试   刚开始学习tf时,我们从 ...

  8. 3.keras-简单实现Mnist数据集分类

    keras-简单实现Mnist数据集分类 1.载入数据以及预处理 import numpy as np from keras.datasets import mnist from keras.util ...

  9. 6.keras-基于CNN网络的Mnist数据集分类

    keras-基于CNN网络的Mnist数据集分类 1.数据的载入和预处理 import numpy as np from keras.datasets import mnist from keras. ...

随机推荐

  1. java导出Excel定义导出模板

    在很多系统功能中都会有Excel导入导出功能,小编采用JXLS工具,简单.灵活. JXLS是基于 Jakarta POI API 的Excel报表生成工具,它采用标签的方式,类似于jsp页面的EL表达 ...

  2. 介绍一下Spring Cloud Config

    Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持.使用Config Server,您可以在所有环境中管理应用程序的外部属性.客户端和服务器上的概念映射与Spring ...

  3. leetcode日记 HouseRobber I II

    House Robber I You are a professional robber planning to rob houses along a street. Each house has a ...

  4. web前端的前景

    随着时代的发展,现在从事IT方向的人有很多,所以励志要成为前端开发工程师的人有很多.当然也有很多人在犹豫不知道该从事哪个方向,我今天就是来给大家分析一下Web前端开发的前景.包括工作内容,发展前景和薪 ...

  5. Unity Canvas vs Panel

    Unity guys specifically gave a performance talk about UI Canvases on some of the past Unite(s). You ...

  6. linux运维工作内容及岗位要求

    什么是Linux?大家日常使用电脑听歌.打游戏娱乐或处理日常工作时,接触到最多的就是Windows操作系统,电脑如果不安装Windows系统是无法进行娱乐和工作的,所有的软件程序都必须运行在操作系统之 ...

  7. linux-docker下安装禅道全部

    友情提示:按照步骤走,99%的人会安装成功,1%的人可以咨询度娘 64位电脑安装禅道,满足发送邮件功能 第一步: docker ps 查看docker中的容器是否有禅道(docker ps -a    ...

  8. 用Spring Boot去创建web service

    1. 环境 JDK1.8 JavaSE1.8 web容器是 webSphere IDE是Eclipse 2. 创建一个空的 Maven Project 3. 打开pom.xml 配置相应的packag ...

  9. web前端技术学习

    $.ajax() ajax数据请求方式,交互,跨域等相关问题 一.请求方式 1.$.ajax() $.ajax({ type:"get",//请求方式“get”和“post” ur ...

  10. Android第二次作业

    另一成员链接:https://www.cnblogs.com/2575590018dqy/p/10053353.html