save_restore_model.py 4.7 KB

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