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