mnist.py 967 B

1234567891011121314151617181920212223242526272829303132333435
  1. import tensorflow as tf
  2. #!/usr/bin/env python
  3. # -*- coding: utf-8 -*-
  4. import tensorflow as tf
  5. import tensorflow.examples.tutorials.mnist.input_data as input_data
  6. mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
  7. sess = tf.InteractiveSession()
  8. x = tf.placeholder("float", shape=[None, 784])
  9. y_ = tf.placeholder("float", shape=[None, 10])
  10. w = tf.Variable(tf.zeros([784,10]))
  11. b = tf.Variable(tf.zeros([10]))
  12. init = tf.global_variables_initializer()
  13. sess.run(init)
  14. y = tf.nn.softmax(tf.matmul(x, w) + b)
  15. cross_entropy = -tf.reduce_sum(y_*tf.log(y))
  16. train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
  17. for i in range(1000):
  18. batch = mnist.train.next_batch(50)
  19. train_step.run(feed_dict={x: batch[0], y_: batch[1]})
  20. correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
  21. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  22. print (accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))