woodsja

eager_mnist.py

Nov 29th, 2018
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. import tensorflow as tf
  2. import numpy as np
  3.  
  4. print(tf.__version__)
  5.  
  6. tf.enable_eager_execution()
  7.  
  8. if tf.executing_eagerly():
  9.   print('eager beaver')
  10.  
  11. x = [[2.]]
  12. m = tf.matmul(x, x)
  13. # print('hello, {}'.format(m))
  14. # formatted string literals look weird
  15. print(f'hello, {m}')
  16.  
  17. # get muh data
  18.  
  19. (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
  20.  
  21. # it has to be as a dictionary
  22. def train_input_fn(images, labels, batch_size):
  23.   # images=dict(images)
  24.   dataset = tf.data.Dataset.from_tensor_slices((
  25.     dict(tf.cast(images / 255, tf.float32)), tf.cast(labels, tf.int64)
  26.   ))
  27.   dataset = dataset.shuffle(100000).repeat().batch(batch_size)
  28.  
  29.   return dataset
  30.  
  31. # train_input_fn(train_images, train_labels, 100)
  32. # rather than providing the raw data directly, we need to provide a function that returns the data
  33.  
  34. # train_input_fn = tf.estimator.inputs.numpy_input_fn(
  35. #   x={'x': np.array(data.x_train)},
  36. #   y=np.array(data.y_train_cls),
  37. #   num_epochs=None,
  38. #   shuffle=True
  39. # )
  40. #
  41. # test_input_fn = tf.estimator.inputs.numpy_input_fn(
  42. #   x={'x': np.array(data.x_test)},
  43. #   y=np.array(data.y_test_cls),
  44. #   num_epochs=1,
  45. #   shuffle=False
  46. # )
  47.  
  48. # build muh feature_column
  49. my_feature_columns = [tf.feature_column.numeric_column('x', shape=[28, 28])]
  50.  
  51. # Spec a classifier
  52. classifier = tf.estimator.DNNClassifier(
  53.   feature_columns=my_feature_columns,
  54.   hidden_units=[256, 32],
  55.   optimizer=tf.train.AdamOptimizer(1e-4),
  56.   n_classes=10,
  57.   dropout=0.1,
  58.   model_dir="./tmp/eager_mnist"
  59. )
  60.  
  61. classifier.train(
  62.   input_fn=lambda: train_input_fn(train_images, train_labels, 100), steps=2000)
  63.  
  64. #cust_train_input_fn = lambda: train_input_fn(mnist_train_images, mnist_train_labels, batch_size=64)
  65.  
  66.  
  67.  
  68.  
  69.  
  70. # # generate testing function
  71. # test_input_function = tf.estimator.inputs.numpy_input_fn(
  72. #   x={'x': input(mnist.test)[0]},
  73. #   y=input(mnist.test)[1],
  74. #   num_epochs=1,
  75. #   shuffle=False
  76. # )
  77.  
  78. # how shall we evaluate our training?
  79. # accuracy_score = classifier.evaluate(input_fn=test_input_function)
  80. # ['accuracy']
  81. # print(f'\nTest Accuracy: {accuracy_score*100}')
Advertisement
Add Comment
Please, Sign In to add comment