save_restore_model.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. '''
  2. Save and Restore a model using TensorFlow.
  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. # Import MINST data
  9. from tensorflow.examples.tutorials.mnist import input_data
  10. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  11. import tensorflow as tf
  12. # Parameters
  13. learning_rate = 0.001
  14. batch_size = 100
  15. display_step = 1
  16. model_path = "/tmp/model.ckpt"
  17. # Network Parameters
  18. n_hidden_1 = 256 # 1st layer number of features
  19. n_hidden_2 = 256 # 2nd layer number of features
  20. n_input = 784 # MNIST data input (img shape: 28*28)
  21. n_classes = 10 # MNIST total classes (0-9 digits)
  22. # tf Graph input
  23. x = tf.placeholder("float", [None, n_input])
  24. y = tf.placeholder("float", [None, n_classes])
  25. # Create model
  26. def multilayer_perceptron(x, weights, biases):
  27. # Hidden layer with RELU activation
  28. layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
  29. layer_1 = tf.nn.relu(layer_1)
  30. # Hidden layer with RELU activation
  31. layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
  32. layer_2 = tf.nn.relu(layer_2)
  33. # Output layer with linear activation
  34. out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
  35. return out_layer
  36. # Store layers weight & bias
  37. weights = {
  38. 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
  39. 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
  40. 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
  41. }
  42. biases = {
  43. 'b1': tf.Variable(tf.random_normal([n_hidden_1])),
  44. 'b2': tf.Variable(tf.random_normal([n_hidden_2])),
  45. 'out': tf.Variable(tf.random_normal([n_classes]))
  46. }
  47. # Construct model
  48. pred = multilayer_perceptron(x, weights, biases)
  49. # Define loss and optimizer
  50. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
  51. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
  52. # Initializing the variables
  53. init = tf.initialize_all_variables()
  54. # 'Saver' op to save and restore all the variables
  55. saver = tf.train.Saver()
  56. # Running first session
  57. print "Starting 1st session..."
  58. with tf.Session() as sess:
  59. # Initialize variables
  60. sess.run(init)
  61. # Training cycle
  62. for epoch in range(3):
  63. avg_cost = 0.
  64. total_batch = int(mnist.train.num_examples/batch_size)
  65. # Loop over all batches
  66. for i in range(total_batch):
  67. batch_x, batch_y = mnist.train.next_batch(batch_size)
  68. # Run optimization op (backprop) and cost op (to get loss value)
  69. _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
  70. y: batch_y})
  71. # Compute average loss
  72. avg_cost += c / total_batch
  73. # Display logs per epoch step
  74. if epoch % display_step == 0:
  75. print "Epoch:", '%04d' % (epoch+1), "cost=", \
  76. "{:.9f}".format(avg_cost)
  77. print "First Optimization Finished!"
  78. # Test model
  79. correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
  80. # Calculate accuracy
  81. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  82. print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
  83. # Save model weights to disk
  84. save_path = saver.save(sess, model_path)
  85. print "Model saved in file: %s" % save_path
  86. # Running a new session
  87. print "Starting 2nd session..."
  88. with tf.Session() as sess:
  89. # Initialize variables
  90. sess.run(init)
  91. # Restore model weights from previously saved model
  92. load_path = saver.restore(sess, model_path)
  93. print "Model restored from file: %s" % save_path
  94. # Resume training
  95. for epoch in range(7):
  96. avg_cost = 0.
  97. total_batch = int(mnist.train.num_examples / batch_size)
  98. # Loop over all batches
  99. for i in range(total_batch):
  100. batch_x, batch_y = mnist.train.next_batch(batch_size)
  101. # Run optimization op (backprop) and cost op (to get loss value)
  102. _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
  103. y: batch_y})
  104. # Compute average loss
  105. avg_cost += c / total_batch
  106. # Display logs per epoch step
  107. if epoch % display_step == 0:
  108. print "Epoch:", '%04d' % (epoch + 1), "cost=", \
  109. "{:.9f}".format(avg_cost)
  110. print "Second Optimization Finished!"
  111. # Test model
  112. correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
  113. # Calculate accuracy
  114. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  115. print "Accuracy:", accuracy.eval(
  116. {x: mnist.test.images, y: mnist.test.labels})