import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# placeholder 占位符
# 通过二维的浮点张量来表示图, None为第一维度
x = tf.placeholder("float", [None, 784])
# variable 变量, 用 zeros来初始化W,b
# W的维度为[784, 10] 由784维的图片得到10维的证据向量
W = tf.Variable(tf.zeros([784, 10]))
# b的形状为10
b = tf.Variable(tf.zeros([10]))
# 套用函式
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 添加新的占位,用于计算交叉熵
y_ = tf.placeholder("float", [None, 10])
# 计算交叉熵
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
# 梯度下降算法
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# 初始化创建变量
init = tf.global_variables_initializer()
# 调用模型
sess = tf.Session()
sess.run(init)
# 训练模型
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 判断预测结果是否跟真是标签匹配
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
# 将布尔值转换为浮点数然后取平均值
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
# 输出所得准确率
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))