test.py 1008 B

123456789101112131415161718192021222324252627282930313233
  1. import tensorflow as tf
  2. import import_data
  3. mnist = import_data.read_data_sets("./", one_hot=True)
  4. # Define variables
  5. x = tf.placeholder("float", [None, 784])
  6. W = tf.Variable(tf.zeros([784, 10]))
  7. b = tf.Variable(tf.zeros([10]))
  8. # Softmax(Wx+b) neural network
  9. y = tf.nn.softmax(tf.matmul(x,W) + b)
  10. # Cross-entropy function for training evaluation
  11. y_ = tf.placeholder("float", [None, 10])
  12. cross_entropy = -tf.reduce_sum(y_*tf.log(y))
  13. train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
  14. init = tf.initialize_all_variables()
  15. session = tf.Session()
  16. session.run(init)
  17. # Train by stochastic gradient descent
  18. for i in xrange(1000):
  19. batch_xs, batch_ys = mnist.train.next_batch(100)
  20. session.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  21. # Evaluate our training
  22. correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
  23. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  24. print session.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})