graph_visualization.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. '''
  2. Graph 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. # Launch the graph
  33. with tf.Session() as sess:
  34. sess.run(init)
  35. # Set logs writer into folder /tmp/tensorflow_logs
  36. summary_writer = tf.train.SummaryWriter('/tmp/tensorflow_logs', graph_def=sess.graph_def)
  37. # Training cycle
  38. for epoch in range(training_epochs):
  39. avg_cost = 0.
  40. total_batch = int(mnist.train.num_examples/batch_size)
  41. # Loop over all batches
  42. for i in range(total_batch):
  43. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  44. # Fit training using batch data
  45. sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
  46. # Compute average loss
  47. avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
  48. # Display logs per epoch step
  49. if epoch % 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(activation, 1), tf.argmax(y, 1))
  54. # Calculate accuracy
  55. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  56. print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
  57. '''
  58. Run the command line: tensorboard --logdir=/tmp/tensorflow_logs
  59. Open http://localhost:6006/ into your web browser
  60. '''