Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. import os
  2. import tensorflow as tf
  3. import numpy as np
  4.  
  5. models_path = os.environ.get("MNIST_MODELS_DIR", "models/mnist")
  6. base_path = os.environ.get("MNIST_DATA_DIR", "data/mnist")
  7. train_file = "train.npz"
  8. test_file = "t10k.npz"
  9.  
  10. learning_rate = float(os.environ.get("LEARNING_RATE", 0.01))
  11. num_steps = int(os.environ.get("LEARNING_STEPS", 10000))
  12. batch_size = int(os.environ.get("BATCH_SIZE", 256))
  13.  
  14.  
  15. def input_fn(file):
  16. with np.load(os.path.join(base_path, file)) as data:
  17. imgs = data["imgs"]
  18. labels = data["labels"].astype(int)
  19. return tf.estimator.inputs.numpy_input_fn(
  20. x = {"imgs": imgs}, y=labels, shuffle=True, batch_size=batch_size)
  21.  
  22. if __name__ == "__main__":
  23. tf.logging.set_verbosity(tf.logging.INFO)
  24.  
  25. # Prepare data inputs
  26. imgs = tf.feature_column.numeric_column("imgs", shape=(28,28))
  27. train_fn, test_fn = input_fn(train_file), input_fn(test_file)
  28.  
  29. # Create the model
  30. estimator = tf.estimator.DNNClassifier(
  31. n_classes=10,
  32. hidden_units=[256, 64],
  33. feature_columns=[imgs],
  34. optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate))
  35.  
  36. # Train and evaluate the model
  37. train_spec = tf.estimator.TrainSpec(input_fn=train_fn, max_steps=num_steps)
  38. eval_spec = tf.estimator.EvalSpec(input_fn=test_fn)
  39. tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
  40.  
  41. # Export the model
  42. serving_input_receiver_fn = tf.estimator \
  43. .export.build_raw_serving_input_receiver_fn(
  44. {"imgs": tf.placeholder(tf.float32, shape=(None, 28, 28))})
  45. estimator.export_savedmodel(models_path, serving_input_receiver_fn)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement