1.了解MNIST数据集
1.1下载MNIST数据集:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot = True)
运行上面代码,会自动将 MNIST数据集 下载并存入指定文件夹。注意,如果网速太慢,会导致下载失败,程序报错。
1.2了解MNIST数据集
(1)MNIST数据集中的图片尺寸是(28*28)Pixel的,每一张图片是一个包含784个Pixel的向量(784 = 28*28)。
#随便读取train中一张图片,查看其大小
im = mnist.train.images[6]
print(im.shape)
(784,)
#784个Pixel的一维向量。
#将图片显示出来
#先将(784,)转换成(28,28)的矩阵
im = im.reshape(-1,28)
print(im.shape)
#导入pylab
import pylab
pylab.imshow(im)
pylab.show()
(2)MNIST由3个数据集组成,分别是train,test,validation(验证),以下代码可查看它们的大小。
print('train集的大小是:' , mnist.train.images.shape)
print('test集的大小是:' , mnist.test.images.shape)
print('validation集的大小是:' , mnist.validation.images.shape)
(3)上述3个数据集图片分别对应有3个标签文件(labels),这些标签对应0~9之间的数,总共10类,采用的是one-hot(又称独热)向量表示。
***注***:0的one_hot为(1000000000);1的one_hot为(0100000000)....
#读取train集对应的标签集
labels = mnist.train.labels
print(labels.shape)
(55000, 10)
#读取其中一个标签进行查看
label = labels[6]
print(label.shape)
print(label)
(10,)
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
2.实验
代码如下
import tensorflow as tf
import pylab
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
#定义图片和标签的占位符
#None 表示张量的第一维度可以接受任意长度
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
#定义权重及偏置值变量
W = tf.Variable(tf.random_normal(([784,10])))
b = tf.Variable(tf.zeros([10]))
#定义输出节点
#softmax是激活函数
pred = tf.nn.softmax(tf.matmul(x,W) + b)
#定义交叉熵
cross_entropy = -tf.reduce_sum(y*tf.log(pred),reduction_indices=1)
#定义损失函数
loss = tf.reduce_mean(cross_entropy)
#定义学习率
learning_rate = 0.01
#定义优化器
opt = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
#定义参数
#总共循环训练轮数
train_epochs = 25
#每轮循环中,每次训练的图片张数
batch_size = 100
#将所有图片训练一轮所需要的总的训练次数
total_batch = int(mnist.train.num_examples/batch_size)
#启动session
with tf.Session() as sess:
#初始化变量,必写
sess.run(tf.global_variables_initializer())
print("以下是训练模型每轮训练误差:")
#循环训练
for epoch in range(train_epochs):
#定义平均loss值
avg_loss = 0.
#循环所有数据
for i in range(total_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
_,c = sess.run([opt,loss],feed_dict={x:batch_xs,y:batch_ys})
#平均loss
avg_loss += c / total_batch
#显示每轮的结果
print('Epoch:',epoch+1,', loss:','{:.9f}'.format(avg_loss))
print("\n训练模型结束,以下是测试模型准确率:")
#以下是测试模型
correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
#准确率:
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print('Accuracy:',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))