In [45]:
from tensorflow.examples.tutorials.mnist import input_data

In [46]:
import tensorflow as tf

In [47]:
mnist = input_data.read_data_sets('/tmp/tensorflow/mnist/input_data', one_hot=True)


Extracting /tmp/tensorflow/mnist/input_data\train-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data\train-labels-idx1-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data\t10k-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data\t10k-labels-idx1-ubyte.gz

In [48]:
# 定义会规模
x = tf.placeholder(tf.float32,[None,784])
w = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x,w) + b  # 预测值

In [49]:
# 定义损失函数和优化器
y_ = tf.placeholder(tf.float32,[None,10]) # 输入的真实值的占位符
# 使用tf.nn.softmax_cross_entropy_with_logits 来计算预测值与真实值的差值 并取均值
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# 采用SGD作为优化器
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

In [50]:
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

In [51]:
#train
for _ in range(1000):
    batch_xs,batch_ys = mnist.train.next_batch(100)
    sess.run(train_step,feed_dict={x: batch_xs,y_:batch_ys})

In [52]:
# 评估训练好的模型
correct_prediction = tf.equal(tf.arg_max(y,1),tf.arg_max(y_,1)) # 计算预测值和真实值
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) # 布尔型转化为浮点数 并取平均值 得到准确率
print(sess.run(accuracy,feed_dict={x: mnist.test.images,y_: mnist.test.labels}))


0.9199