logistic_regression_eager_api.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. ''' Logistic Regression with Eager API.
  2. A logistic regression learning algorithm example using TensorFlow's Eager API.
  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 absolute_import, division, print_function
  9. import tensorflow as tf
  10. # Set Eager API
  11. tf.enable_eager_execution()
  12. tfe = tf.contrib.eager
  13. # Import MNIST data
  14. from tensorflow.examples.tutorials.mnist import input_data
  15. mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)
  16. # Parameters
  17. learning_rate = 0.1
  18. batch_size = 128
  19. num_steps = 1000
  20. display_step = 100
  21. dataset = tf.data.Dataset.from_tensor_slices(
  22. (mnist.train.images, mnist.train.labels))
  23. dataset = dataset.repeat().batch(batch_size).prefetch(batch_size)
  24. dataset_iter = tfe.Iterator(dataset)
  25. # Variables
  26. W = tfe.Variable(tf.zeros([784, 10]), name='weights')
  27. b = tfe.Variable(tf.zeros([10]), name='bias')
  28. # Logistic regression (Wx + b)
  29. def logistic_regression(inputs):
  30. return tf.matmul(inputs, W) + b
  31. # Cross-Entropy loss function
  32. def loss_fn(inference_fn, inputs, labels):
  33. # Using sparse_softmax cross entropy
  34. return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
  35. logits=inference_fn(inputs), labels=labels))
  36. # Calculate accuracy
  37. def accuracy_fn(inference_fn, inputs, labels):
  38. prediction = tf.nn.softmax(inference_fn(inputs))
  39. correct_pred = tf.equal(tf.argmax(prediction, 1), labels)
  40. return tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  41. # SGD Optimizer
  42. optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
  43. # Compute gradients
  44. grad = tfe.implicit_gradients(loss_fn)
  45. # Training
  46. average_loss = 0.
  47. average_acc = 0.
  48. for step in range(num_steps):
  49. # Iterate through the dataset
  50. d = dataset_iter.next()
  51. # Images
  52. x_batch = d[0]
  53. # Labels
  54. y_batch = tf.cast(d[1], dtype=tf.int64)
  55. # Compute the batch loss
  56. batch_loss = loss_fn(logistic_regression, x_batch, y_batch)
  57. average_loss += batch_loss
  58. # Compute the batch accuracy
  59. batch_accuracy = accuracy_fn(logistic_regression, x_batch, y_batch)
  60. average_acc += batch_accuracy
  61. if step == 0:
  62. # Display the initial cost, before optimizing
  63. print("Initial loss= {:.9f}".format(average_loss))
  64. # Update the variables following gradients info
  65. optimizer.apply_gradients(grad(logistic_regression, x_batch, y_batch))
  66. # Display info
  67. if (step + 1) % display_step == 0 or step == 0:
  68. if step > 0:
  69. average_loss /= display_step
  70. average_acc /= display_step
  71. print("Step:", '%04d' % (step + 1), " loss=",
  72. "{:.9f}".format(average_loss), " accuracy=",
  73. "{:.4f}".format(average_acc))
  74. average_loss = 0.
  75. average_acc = 0.
  76. # Evaluate model on the test image set
  77. testX = mnist.test.images
  78. testY = mnist.test.labels
  79. test_acc = accuracy_fn(logistic_regression, testX, testY)
  80. print("Testset Accuracy: {:.4f}".format(test_acc))