logistic_regression.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. '''
  2. A logistic regression learning algorithm example using TensorFlow library.
  3. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
  4. Author: Aymeric Damien
  5. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  6. '''
  7. # Import MINST data
  8. import input_data
  9. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  10. import tensorflow as tf
  11. # Parameters
  12. learning_rate = 0.01
  13. training_epochs = 25
  14. batch_size = 100
  15. display_step = 1
  16. # tf Graph Input
  17. x = tf.placeholder("float", [None, 784]) # mnist data image of shape 28*28=784
  18. y = tf.placeholder("float", [None, 10]) # 0-9 digits recognition => 10 classes
  19. # Create model
  20. # Set model weights
  21. W = tf.Variable(tf.zeros([784, 10]))
  22. b = tf.Variable(tf.zeros([10]))
  23. # Construct model
  24. activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
  25. # Minimize error using cross entropy
  26. cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(activation), reduction_indices=1)) # Cross entropy
  27. optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Gradient Descent
  28. # Initializing the variables
  29. init = tf.initialize_all_variables()
  30. # Launch the graph
  31. with tf.Session() as sess:
  32. sess.run(init)
  33. # Training cycle
  34. for epoch in range(training_epochs):
  35. avg_cost = 0.
  36. total_batch = int(mnist.train.num_examples/batch_size)
  37. # Loop over all batches
  38. for i in range(total_batch):
  39. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  40. # Fit training using batch data
  41. sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
  42. # Compute average loss
  43. avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
  44. # Display logs per epoch step
  45. if epoch % display_step == 0:
  46. print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
  47. print "Optimization Finished!"
  48. # Test model
  49. correct_prediction = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1))
  50. # Calculate accuracy
  51. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  52. print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})