loss_visualization.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. '''
  2. Loss Visualization with TensorFlow.
  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 tensorflow as tf
  8. import numpy
  9. # Import MINST data
  10. import input_data
  11. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  12. # Use Logistic Regression from our previous example
  13. # Parameters
  14. learning_rate = 0.01
  15. training_epochs = 10
  16. batch_size = 100
  17. display_step = 1
  18. # tf Graph Input
  19. x = tf.placeholder("float", [None, 784], name='x') # mnist data image of shape 28*28=784
  20. y = tf.placeholder("float", [None, 10], name='y') # 0-9 digits recognition => 10 classes
  21. # Create model
  22. # Set model weights
  23. W = tf.Variable(tf.zeros([784, 10]), name="weights")
  24. b = tf.Variable(tf.zeros([10]), name="bias")
  25. # Construct model
  26. activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
  27. # Minimize error using cross entropy
  28. cost = -tf.reduce_sum(y*tf.log(activation)) # Cross entropy
  29. optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Gradient Descent
  30. # Initializing the variables
  31. init = tf.initialize_all_variables()
  32. # Create a summary to monitor cost function
  33. tf.scalar_summary("loss", cost)
  34. # Merge all summaries to a single operator
  35. merged_summary_op = tf.merge_all_summaries()
  36. # Launch the graph
  37. with tf.Session() as sess:
  38. sess.run(init)
  39. # Set logs writer into folder /tmp/tensorflow_logs
  40. summary_writer = tf.train.SummaryWriter('/tmp/tensorflow_logs', graph_def=sess.graph_def)
  41. # Training cycle
  42. for epoch in range(training_epochs):
  43. avg_cost = 0.
  44. total_batch = int(mnist.train.num_examples/batch_size)
  45. # Loop over all batches
  46. for i in range(total_batch):
  47. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  48. # Fit training using batch data
  49. sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
  50. # Compute average loss
  51. avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
  52. # Write logs at every iteration
  53. summary_str = sess.run(merged_summary_op, feed_dict={x: batch_xs, y: batch_ys})
  54. summary_writer.add_summary(summary_str, epoch*total_batch + i)
  55. # Display logs per epoch step
  56. if epoch % display_step == 0:
  57. print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
  58. print "Optimization Finished!"
  59. # Test model
  60. correct_prediction = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1))
  61. # Calculate accuracy
  62. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  63. print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
  64. '''
  65. Run the command line: tensorboard --logdir=/tmp/tensorflow_logs
  66. Open http://localhost:6006/ into your web browser
  67. '''