MNIST 个人理解
一、MNIST介绍
mnist手写体识别是图像识别中最经典的问题, 希望能够识别出人类手写的数字. 数据是65000张灰度图和对应的数字。
二、使用深度神经网络进行学习(DNN)
1、导入需要用到的包
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import tensorflow as tf
import numpy as np
2、导入mnist 数据集(mnist数据集成在 tensorflow.examples 里)
import tensorflow.examples.tutorials.mnist.input_data as input_data
tf.set_random_seed(2017) # 设置种子,使每次的随机数相同
3、MNIST_data数据包
(导入成功会出现以下信息)
train-images-idx3-ubyte.gz
train-labels-idx1-ubyte.gz
t10k-images-idx3-ubyte.gz
t10k-labels-idx1-ubyte.gz
4、开始定义深度网络结构
# 将数据输入 one_hot参数:将一个数值n映射到一个向量, 这个向量的第n个元素是1, 其他元素都是0,因为我们识别的是0~9的某一数字,所以每一张图片都是对应一个数字的
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 将mnist数据集分为训练集和测试集
train_set = mnist.train
test_set = mnist.test
# 定义hidden_layer(隐藏层)函数
def hidden_layer(layer_input, output_depth, scope='hidden_layer', reuse=None):
input_depth = layer_input.get_shape()[-1]
with tf.variable_scope(scope, reuse=reuse):
# 注意这里的初始化方法是truncated_normal
w = tf.get_variable(initializer=tf.truncated_normal_initializer(stddev=0.1),shape=(input_depth, output_depth), name='weights')
# 注意这里用 0.1 对偏置进行初始化
b = tf.get_variable(initializer=tf.constant_initializer(0.1), shape=(output_depth), name='bias')
net = tf.matmul(layer_input, w) + b
return net
# 构造DNN(深度神经网络)
def DNN(x, output_depths, scope='DNN', reuse=None):
net = x
for i, output_depth in enumerate(output_depths):
net = hidden_layer(net, output_depth, scope='layer%d'%i, reuse=reuse)
# 注意这里的激活函数
net = tf.nn.relu(net
# 数字分为0, 1, ..., 9 所以这是10分类问题
# 对应于 one_hot 的标签, 所以这里输出一个 10维的向量
net = hidden_layer(net, 10, scope='classification', reuse=reuse)
return net
# 定义占位符
input_ph = tf.placeholder(shape=(None, 784), dtype=tf.float32)
label_ph = tf.placeholder(shape=(None, 10), dtype=tf.int64)
# 构造一个4层的神经网络, 它的隐藏节点数分别为: 400, 200, 100, 10
dnn = DNN(input_ph, [400, 200, 100])
# 这是一个分类问题, 因此我们采用交叉熵来计算损失函数
loss = tf.losses.softmax_cross_entropy(logits=dnn, onehot_labels=label_ph)
# 下面定义的是正确率, 注意理解它为什么是这么定义的
acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(dnn, axis=-1), tf.argmax(label_ph,axis=-1)), dtype=tf.float32))
# 学习率
lr = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate=lr)
train_op = optimizer.minimize(loss)
sess = tf.InteractiveSession()
# 我们训练2000次
batch_size = 64
sess.run(tf.global_variables_initializer())
for e in range(2000):
# 获取 batch_size个训练样本
images, labels = train_set.next_batch(batch_size)
sess.run(train_op, feed_dict={input_ph: images, label_ph: labels})
if e%100 == 99:
# 获取 batch_size 个测试样本
test_imgs, test_labels = test_set.next_batch(batch_size)
# 计算在当前样本上的训练以及测试样本的损失值和正确率
loss_train, acc_train = sess.run([loss, acc], feed_dict={input_ph: images,label_ph: labels})
loss_test, acc_test = sess.run([loss, acc], feed_dict={input_ph: test_imgs,label_ph: test_labels})
print('STEP {}: train_loss: {:.6f} train_acc: {:.6f} test_loss: {:.6f}test_acc: {:.6f}'.format(e+1, loss_train, acc_train, loss_test, acc_test))
print('Train Done!')
print('-'*30)
# 计算所有训练样本的损失值以及正确率
train_loss = []
train_acc = []
for _ in range(train_set.num_examples//100):
image, label = train_set.next_batch(100)
loss_train, acc_train = sess.run([loss, acc], feed_dict={input_ph: image,label_ph: label})
train_loss.append(loss_train)
train_acc.append(acc_train)
print('Train loss: {:.6f}'.format(np.array(train_loss).mean()))
print('Train accuracy: {:.6f}'.format(np.array(train_acc).mean()))
# 计算所有测试样本的损失值以及正确率
test_loss = []
test_acc = []
for _ in range(test_set.num_examples//100):
image, label = test_set.next_batch(100)
loss_test, acc_test = sess.run([loss, acc], feed_dict={input_ph: image, label_ph:label})
test_loss.append(loss_test)
test_acc.append(acc_test)
print('Test loss: {:.6f}'.format(np.array(test_loss).mean()))
print('Test accuracy: {:.6f}'.format(np.array(test_acc).mean()))
5、训练结果
6、测试集结果(部分)
写在最后
如果有不懂的小伙伴,可以关注我的微信公众号:人工智能TensorFlow学习 ,一起交流学习。