logistic_regression.py 2.2 KB

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