参考 MNIST数据集手写数字分类 - 云+社区 - 腾讯云
目录
MNIST是Mixed National Institue of Standards and Technology database的简称,中文叫做美国国家标准与技术研究所数据库。
0.编程环境
安装tensorflow命令:pip install tensorflow
操作系统:Win10
python版本:3.6
集成开发环境:jupyter notebook
tensorflow版本:1.6
1、下载并解压数据集
MNIST数据集下载链接: 百度网盘 请输入提取码 密码: wa9p
下载压缩文件MNIST_data.rar完成后,选择解压到当前文件夹,不要选择解压到MNIST_data。
文件夹结构如下图所示:
2、完整代码
此章给读者能够直接运行的完整代码,使读者有编程结果的感性认识。
如果下面一段代码运行成功,则说明安装tensorflow环境成功。
想要了解代码的具体实现细节,请阅读后面的章节。
import warnings
warnings.filterwarnings('ignore')
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
batch_size = 100
X_holder = tf.placeholder(tf.float32)
y_holder = tf.placeholder(tf.float32)
Weights = tf.Variable(tf.zeros([784, 10]))
biases = tf.Variable(tf.zeros([1,10]))
predict_y = tf.nn.softmax(tf.matmul(X_holder, Weights) + biases)
loss = tf.reduce_mean(-tf.reduce_sum(y_holder * tf.log(predict_y), 1))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)
for i in range(500):
images, labels = mnist.train.next_batch(batch_size)
session.run(train, feed_dict={X_holder:images, y_holder:labels})
if i % 25 == 0:
correct_prediction = tf.equal(tf.argmax(predict_y, 1), tf.argmax(y_holder, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
accuracy_value = session.run(accuracy, feed_dict={X_holder:mnist.test.images, y_holder:mnist.test.labels})
print('step:%d accuracy:%.4f' %(i, accuracy_value))
上面一段代码的运行结果如下:
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
step:0 accuracy:0.4747
step:25 accuracy:0.8553
step:50 accuracy:0.8719
step:75 accuracy:0.8868
step:100 accuracy:0.8911
step:125 accuracy:0.8998
step:150 accuracy:0.8942
step:175 accuracy:0.9050
step:200 accuracy:0.9026
step:225 accuracy:0.9076
step:250 accuracy:0.9071