logistic_regression.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. # Initialize the variables (i.e. assign their default value)
  31. init = tf.global_variables_initializer()
  32. # Start training
  33. with tf.Session() as sess:
  34. # Run the initializer
  35. sess.run(init)
  36. # Training cycle
  37. for epoch in range(training_epochs):
  38. avg_cost = 0.
  39. total_batch = int(mnist.train.num_examples/batch_size)
  40. # Loop over all batches
  41. for i in range(total_batch):
  42. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  43. # Run optimization op (backprop) and cost op (to get loss value)
  44. _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
  45. y: batch_ys})
  46. # Compute average loss
  47. avg_cost += c / total_batch
  48. # Display logs per epoch step
  49. if (epoch+1) % display_step == 0:
  50. print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
  51. print("Optimization Finished!")
  52. # Test model
  53. correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
  54. # Calculate accuracy
  55. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  56. print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))