MNIST数据集是NIST的子集,包含了60000张图片为训练数据,10000张作为测试数据,其中包含了训练数据与测试数据的图片及答案,每项图片的大小为28×28,数字都出现在图片的正中间。
而TensorFlow提供了一个类处理MNIST,将图片解析成需要的格式:
from tensorflow.examples.tutorials.mnist import input_data
# 载入数据集
mnist = input_data.read_data_sets("E:/minst", one_hot=True)
print("training datasize:", mnist.train.num_examples)
print("validating data size:", mnist.validation.num_examples)
print("testing data size:", mnist.test.num_examples)
print("Example training data: ", mnist.train.images[0])
print("Example training data label: ", mnist.train.labels[0])
以下为解决手写体识别的程序实例:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#数据集相关常数
INPUT_NODE = 784
OUTPUT_NODE = 10
#隐层节点
LAYER1_NODE = 500
BATCH_SIZE = 100
#
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99
REGULARIZATION_RATE = 0.0001#正则化系数
TRAINING_STEPS = 30000
MOVING_AVERAGE_DECAY = 0.99
#辅助函数
def inference(input_tensor, avg_class, weights1, biases1, weights2, biases2):
if avg_class is None:
layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)
return tf.matmul(layer1, weights2) + biases2
else:
layer1 = tf.nn.relu(
tf.matmul(input_tensor, avg_class.average(weights1)) + avg_class.average(biases1))
return tf.matmul(layer1, avg_class.average(weights2)) + avg_class.average(biases2)
def train(mnist):
x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE],name="y-input")
#生成隐层
weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE],stddev=0.1))
biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))
#生成输出层的参数
weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))
biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))
#计算当前参数下神经网络前向传播结果,avg_class = None
y = inference(x, None, weights1, biases1, weights2, biases2)
#将代表训练轮数的变量指定为不可训练
global_step = tf.Variable(0, trainable=False)
#初始化滑动平均类
variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
#对所有神经网络变量使用滑动平均。
variable_averages_op = variable_averages.apply(tf.trainable_variables())
#计算使用滑动平均后的前向传播结果
average_y = inference(x, variable_averages, weights1, biases1,weights2,biases2)
#交叉熵
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=y, labels=tf.arg_max(y_, 1))
#交叉熵平均值
cross_entropy_mean = tf.reduce_mean(cross_entropy)
#L2正则化
regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
#计算正则化损失
regularization = regularizer(weights1) + regularizer(weights2)
#总损失
loss = cross_entropy_mean + regularization
#学习率
learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,
global_step,
mnist.train.num_examples,
LEARNING_RATE_DECAY)
#梯度下降优化损失函数
train_step = tf.train.GradientDescentOptimizer(learning_rate).\
minimize(loss, global_step=global_step)
with tf.control_dependencies([train_step, variable_averages_op]):
train_op = tf.no_op(name='train')
# 计算每一个样例的预测答案。其中average_y是一个batch_size*10的二维数组,
# 每一行表示一个样例的前向传播结果
# tf.argmax的第二个参数表示选取最大值的操作仅在第一个维度中进行,也就是说,
# 只在每一行选取最大值对应的下标。
# 于是得到的结果是一个长度为batch的一维数组,这个一维数组中的值表示每一个
# 样例对应的数字识别结果
# tf.equal判断两个张量的每一维是否相等,相等返回true
correct_predition = tf.equal(tf.arg_max(average_y, 1), tf.arg_max(y_,1))
#将bool转换为实数,再计算平均值
accuracy = tf.reduce_mean(tf.cast(correct_predition,tf.float32))
#开始训练
with tf.Session() as sess:
tf.global_variables_initializer().run()
#验证数据,来判断停止的条件和评判训练的效果
validate_feed = {x: mnist.validation.images,
y_: mnist.validation.labels}
#准备测试数据
test_feed = {x: mnist.test.images, y_:mnist.test.labels}
#迭代训练
for i in range(TRAINING_STEPS):
if i % 1000 == 0:
validate_acc = sess.run(accuracy, feed_dict=validate_feed)
print("after %d training step(s), test ac"
"curacy using average "\
"model is %g " %(i, validate_acc))
xs, ys = mnist.train.next_batch(BATCH_SIZE)
sess.run(train_op, feed_dict={x: xs, y_: ys})
test_acc = sess.run(accuracy, feed_dict=test_feed)
print("after %d training step(s), test accuracy using average"
"model is %g "%(TRAINING_STEPS, test_acc))
def main(argv = None):
#声明处理MNIST数据集的类
mnist = input_data.read_data_sets("E:/minst", one_hot=True)
train(mnist)
if __name__ == '__main__':
tf.app.run()
mnist.train.next_batch可以从所有训练数据中读出一小部分作为一个训练batch,方便使用随机梯度下降算法
来源:CSDN
作者:Burger.Z
链接:https://blog.csdn.net/weixin_43900469/article/details/104194490