1. 首先下载MNIST (这里采用离线下载再读取的方法。在线安装由于SSL权限的问题,可以参考
http://www.tensorfly.cn/tfdoc/tutorials/mnist_download.html )
2.读入MNIST
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
MNIST_dir = 'C:\\Users\\HAPPY\\Desktop\\mnist' #MNIST文件夹目录
mnist = input_data.read_data_sets(MNIST_dir, one_hot=True)
3.训练代码(此处训练10000次,设置学习率为0.03,最后调出的识别准确率为89%左右)
# coding:utf-8
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
MNIST_dir = 'C:\\Users\\HAPPY\\Desktop\\mnist'
mnist = input_data.read_data_sets(MNIST_dir, one_hot=True)
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, w) + b)
loss = -tf.reduce_mean(y_ * tf.log(y))
train_steps = tf.train.GradientDescentOptimizer(0.03).minimize(loss)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(10000):
batch_x, batch_y = mnist.train.next_batch(100)
sess.run(train_steps, {x: batch_x, y_: batch_y})
if i % 1000 == 0:
print("now steps: %d" % int(i))
correct_prediction = tf.equal(tf.arg_max(y, 1), tf.argmax(y_, 1)) #测试最后的准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, {x: mnist.test.images, y_: mnist.test.labels}))