tensorflow实现Minist手写体识别

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

#下载MINIST数据集

mnist = input_data.read_data_sets(\'MNIST_data\', one_hot=True)

#表示输入任意数量的MNIST图像,每一张图展平成784维的向量

#placeholder是占位符,在训练时指定

x = tf.placeholder(tf.float32, [None, 784])

#初始化W,b矩阵

W = tf.Variable(tf.zeros([784,10]))

b = tf.Variable(tf.zeros([10]))

#tf.matmul(​​X,W)表示x乘以W

y = tf.nn.softmax(tf.matmul(x, W) + b)

#为了计算交叉熵,我们首先需要添加一个新的占位符用于输入正确值

y_ = tf.placeholder("float", [None,10])

#交叉熵损失函数

cross_entropy = -tf.reduce_sum(y_*tf.log(y))

#模型的训练,不断的降低成本函数

#要求TensorFlow用梯度下降算法(gradient descent algorithm)以0.01的学习速率最小化交叉熵

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

#在运行计算之前,需要添加一个操作来初始化我们创建的变量

init = tf.initialize_all_variables()

#在Session里面启动我模型,并且初始化变量

sess = tf.Session()

sess.run(init)

#开始训练模型,循环训练1000次

for i in range(50):

  #随机抓取训练数据中的100个批处理数据点

  batch_xs, batch_ys = mnist.train.next_batch(100)

  #然后我们用这些数据点作为参数替换之前的占位符来运行train_step

  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

#检验真实标签与预测标签是否一致

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

#计算精确度,将true和false转化成相应的浮点数,求和取平均

accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

#计算所学习到的模型在测试数据集上面的正确率

print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))