基于tensorflow的手写数字识别
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#每个批次的大小
n_batch = mnist.train.num_examples//batch_size#计算一共有多少个批次
x = tf.placeholder(tf.float32,[None,784])#定义两个变量
y = tf.placeholder(tf.float32,[None,10])
#构建一个简单的神经网络
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)
#二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#初始化变量
init = tf.global_variables_initializer()
#结果存放在布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(21):
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("Iter" + str(epoch) + ",Testing Accuracy" + str(acc))
运行结果:
Iter0,Testing Accuracy0.8318
Iter1,Testing Accuracy0.8697
Iter2,Testing Accuracy0.8817
Iter3,Testing Accuracy0.8878
Iter4,Testing Accuracy0.893
Iter5,Testing Accuracy0.897
Iter6,Testing Accuracy0.8997
Iter7,Testing Accuracy0.9017
Iter8,Testing Accuracy0.9043
Iter9,Testing Accuracy0.9046
Iter10,Testing Accuracy0.906
Iter11,Testing Accuracy0.9078
Iter12,Testing Accuracy0.9083
Iter13,Testing Accuracy0.9091
Iter14,Testing Accuracy0.9102
Iter15,Testing Accuracy0.9106
Iter16,Testing Accuracy0.9118
Iter17,Testing Accuracy0.9122
Iter18,Testing Accuracy0.9129
Iter19,Testing Accuracy0.9135
Iter20,Testing Accuracy0.9133
使用最基本的神经网络准确率可以达到0.9133,该神经网络中有诸多可以修改的地方以提高最终的准确率