认识MINIST数据集
目的 | |
---|---|
data_sets.train |
55000个图像和标签(labels),作为主要训练集。 |
data_sets.validation |
5000个图像和标签,用于迭代验证训练准确度。 |
data_sets.test |
10000个图像和标签,用于最终测试训练准确度(trained accuracy)。 |
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print (mnist.train.images.shape)
print (mnist.train.labels.shape)
print (mnist.validation.images.shape)
print (mnist.validation.labels.shape)
print (mnist.test.images.shape)
print (mnist.test.labels.shape)
输出结果:
Extracting MNIST_data/train-images-idx3-ubyte.gz #训练集图片 - 55000 张 训练图片, 5000 张 验证图片
Extracting MNIST_data/train-labels-idx1-ubyte.gz #训练集图片对应的数字标签
Extracting MNIST_data/t10k-images-idx3-ubyte.gz #测试集图片 - 10000 张 图片
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz #测试集图片对应的数字标签
(55000, 784) #训练集图像的shape
(55000, 10) #训练集图像标签的shape
(5000, 784) #验证集图像的shape
(5000, 10) #验证集图像标签的shape
(10000, 784) #测试集图像的shape
(10000, 10) #测试集图像标签的shape
将数据存为变量,查看数据:
val_data=mnist.validation.images
val_label=mnist.validation.labels
print('验证集图像:\n',val_data)
print('验证集标签:\n',val_label)
输出结果:
验证集图像:
[[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
...,
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]]
验证集标签:
[[ 0. 0. 0. ..., 0. 0. 0.]
[ 1. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
...,
[ 0. 0. 1. ..., 0. 0. 0.]
[ 0. 1. 0. ..., 0. 0. 0.]
[ 0. 0. 1. ..., 0. 0. 0.]]
构建图表 (Build the Graph)
在为数据创建占位符之后,就可以运行mnist.py
文件,经过三阶段的模式函数操作:inference()
,loss()
,和training()
。图表就构建完成了。
1.inference()
—— 尽可能地构建好图表,满足促使神经网络向前反馈并做出预测的要求。
2.loss()
—— 往inference图表中添加生成损失(loss)所需要的操作(ops)。
3.training()
—— 往损失图表中添加计算并应用梯度(gradients)所需的操作。
推理(Inference)
def inference(images, hidden1_units, hidden2_units):
"""构建图表.它接受图像占位符为输入,
在此基础上借助ReLu(Rectified Linear Units)激活函数,
构建一对完全连接层(layers),
以及一个有着十个节点(node)、指明了输出logtis模型的线性层。
Args:
images: 接受图像占位符为输入
hidden1_units: 第一个隐层的大小
hidden2_units: 第二个隐层的大小
Returns:
softmax_linear: 包含预测结果的tensor
"""
# Hidden 1
with tf.name_scope('hidden1'):
weights = tf.Variable(
tf.truncated_normal([IMAGE_PIXELS, hidden1_units],
stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))),
name='weights')
biases = tf.Variable(tf.zeros([hidden1_units]),
name='biases')
hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)
# Hidden 2
with tf.name_scope('hidden2'):
weights = tf.Variable(
tf.truncated_normal([hidden1_units, hidden2_units],
stddev=1.0 / math.sqrt(float(hidden1_units))),
name='weights')
biases = tf.Variable(tf.zeros([hidden2_units]),
name='biases')
hidden2 = tf.nn.relu(tf.matmu