logistic_regression.py 2.2 KB

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