# MNIST数据集分类简单版本（详细）

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
#载入Mnist数据集
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))
init=tf.global_variables_initializer()

#重点理解这两句，有新东西。
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
#tf.argmax(input,axis)根据axis取值的不同返回每行或者每列最大值的索引。axis为1表示取行最大值得索引。
#如果两个值相等，返回TRUE,结果保存的是布尔型的列表
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
#tf.cast()类似强制类型转换，把布尔型变为32位float型，然后求平均。[1,1,1,0,0,0,1,1,1,1],准确率为0.7

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))


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
iter0,Testing Accuracy0.8312
iter1,Testing Accuracy0.8706
iter2,Testing Accuracy0.8814
iter3,Testing Accuracy0.888
iter4,Testing Accuracy0.8938
iter5,Testing Accuracy0.8974
iter6,Testing Accuracy0.9
iter7,Testing Accuracy0.9021
iter8,Testing Accuracy0.9033
iter9,Testing Accuracy0.9049
iter10,Testing Accuracy0.906
iter11,Testing Accuracy0.9076
iter12,Testing Accuracy0.9082
iter13,Testing Accuracy0.9091
iter14,Testing Accuracy0.9095
iter15,Testing Accuracy0.9106
iter16,Testing Accuracy0.9111
iter17,Testing Accuracy0.9124
iter18,Testing Accuracy0.9132
iter19,Testing Accuracy0.9132
iter20,Testing Accuracy0.9139

01-19

03-15 1942
04-01 103
12-16
12-24
06-07 2万+
09-25 57
04-10 94
07-14 7287
12-04