# ====================================================
#tensorflow实现softmax Regression识别手写数字
#
#构造一个简单的神经网络不含隐藏层分成四步
# 1.定义算法公式,前向计算
# 2.定义loss函数,选择优化器,让优化器优化loss
# 3.迭代对数据训练
# 4.用测试数据测得准确率
#
#结构的优化
#
# ====================================================
#载入一个tensorflow库
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)
import tensorflow as tf
#创建一个新的InteractiveSession,使用这个命令会将session注册为默认的session
sess=tf.InteractiveSession()
#----------------------------
#前向计算
#----------------------------
#创建一个placeholder,即数据输入的地方
x=tf.placeholder(tf.float32,[None,784])
#Variable用来存储模型参数
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
#实现softmax函数
y=tf.nn.softmax(tf.matmul(x,W)+b)
#输入y_是真实的lable
y_=tf.placeholder(tf.float32,[None,10])
#----------------------------
#定义损失函数cross_entropy
#----------------------------
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))#tf.reduce_sum按照reduction_indices指定的轴进行求和
#用封装好的优化器优化损失函数cross_entropy
train_step = tf.train.GradientDescentOptimizer(0.8).minimize(cross_entropy)
#----------------------------
#迭代对数据训练
#----------------------------
#全局参数初始化器
tf.global_variables_initializer().run()
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run({x: batch_xs, y_: batch_ys})
#----------------------------
#用测试数据测得准确率
#----------------------------
#计算分类是否正确
#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
#tf.cast将布尔型转换为浮点型
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
#准确率
print(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels}))
# #每个批次的大小
# batch_size = 20
# #计算一共有多少个批次
# n_batch = mnist.train.num_examples // batch_size
# for epoch in range(50):#把所有图片训练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})
# train_step.run({x: batch_xs, y_: batch_ys})
# acc = train_step.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels})#看准确率的变化
# print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))