iam_classifier.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # From the tutorial on
  2. # https://www.tensorflow.org/get_started/mnist/pros
  3. import argparse
  4. import sys
  5. ########################################################################################
  6. # Declare the data format
  7. import random
  8. import _pickle as pickle
  9. N_INPUT = 972
  10. N_OUTPUT = 10 + 26 + 26
  11. class Datum:
  12. def __init__(self, label, img):
  13. self.label = [0] * N_OUTPUT
  14. self.label[label - 1] = 1
  15. self.img = img
  16. class IAM:
  17. def __init__(self):
  18. print("Building dataset...")
  19. self.train = []
  20. self.test = []
  21. for x in range(1, N_OUTPUT + 1):
  22. print("Preparing sample %d..." % x)
  23. for f in os.listdir(DATA_FOLDER % x):
  24. img = scipy.ndimage.imread(IMG_TEMPLATE % (x, f), True)
  25. img = scipy.misc.imresize(img, 0.03)
  26. img = list(itertools.chain.from_iterable(img))
  27. if len(self.test) < (5 * x):
  28. self.test.append(Datum(x, img))
  29. else:
  30. self.train.append(Datum(x, img))
  31. def nextBatch(self, size):
  32. used = []
  33. res = []
  34. labels = []
  35. while len(used) < size:
  36. i = random.randint(0, len(self.train) - 1)
  37. if i in used:
  38. continue
  39. else:
  40. used.append(i)
  41. res.append(self.train[i].img)
  42. labels.append(self.train[i].label)
  43. return res, labels
  44. def testSet(self):
  45. res = []
  46. labels = []
  47. for i in range(0, len(self.test)):
  48. res.append(self.test[i].img)
  49. labels.append(self.test[i].label)
  50. return res, labels
  51. print(sys.argv)
  52. LEARNING_CONST = 0.05
  53. TRAIN_CYCLES = 1000
  54. BATCH_SIZE = 100
  55. # Turn off GPU Warnings/All other warnings
  56. import os
  57. os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
  58. import tensorflow as tf
  59. FLAGS = None
  60. def deepnn(x):
  61. # Reshape to use within a convolutional neural net.
  62. x_image = tf.reshape(x, [-1, 18, 54, 1]) # tf.reshape(x, [-1, 28, 28, 1])
  63. # First convolutional layer - maps one grayscale image to 32 feature maps.
  64. W_conv1 = weight_variable([5, 5, 1, 32])
  65. b_conv1 = bias_variable([32])
  66. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
  67. # Pooling layer - downsamples by 2X.
  68. h_pool1 = max_pool_2x2(h_conv1)
  69. # Second convolutional layer -- maps 32 feature maps to 64.
  70. W_conv2 = weight_variable([5, 5, 32, 64])
  71. b_conv2 = bias_variable([64])
  72. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
  73. # Second pooling layer.
  74. h_pool2 = max_pool_2x2(h_conv2)
  75. # Fully connected layer 1
  76. W_fc1 = weight_variable([7 * 10 * 64, 1024]) # weight_variable([7 * 7 * 64, 1024])
  77. b_fc1 = bias_variable([1024])
  78. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*10*64]) # tf.reshape(h_pool2, [-1, 7*7*64])
  79. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  80. # Dropout - controls the complexity of the model, prevents co-adaptation of
  81. # features.
  82. keep_prob = tf.placeholder(tf.float32)
  83. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  84. # Map the 1024 features to 62 classes, one for each symbol
  85. W_fc2 = weight_variable([1024, 62]) # weight_variable([1024, 10])
  86. b_fc2 = bias_variable([62]) # bias_variable([10])
  87. y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  88. return y_conv, keep_prob
  89. def conv2d(x, W):
  90. """conv2d returns a 2d convolution layer with full stride."""
  91. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  92. def max_pool_2x2(x):
  93. """max_pool_2x2 downsamples a feature map by 2X."""
  94. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
  95. strides=[1, 2, 2, 1], padding='SAME')
  96. def weight_variable(shape):
  97. """weight_variable generates a weight variable of a given shape."""
  98. initial = tf.truncated_normal(shape, stddev=0.1)
  99. return tf.Variable(initial)
  100. def bias_variable(shape):
  101. """bias_variable generates a bias variable of a given shape."""
  102. initial = tf.constant(0.1, shape=shape)
  103. return tf.Variable(initial)
  104. def main(_):
  105. # Import data
  106. # mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  107. with open('iamDataset.obj', 'rb') as input:
  108. iam = pickle.load(input)
  109. # Create the model
  110. x = tf.placeholder(tf.float32, [None, N_INPUT]) # tf.placeholder(tf.float32, [None, 784])
  111. # Define loss and optimizer
  112. y_ = tf.placeholder(tf.float32, [None, 62]) # tf.placeholder(tf.float32, [None, 10])
  113. # Build the graph for the deep net
  114. y_conv, keep_prob = deepnn(x)
  115. cross_entropy = tf.reduce_mean(
  116. tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
  117. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  118. correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
  119. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  120. with tf.Session() as sess:
  121. sess.run(tf.global_variables_initializer())
  122. for i in range(101): # 20000
  123. batch = iam.nextBatch(BATCH_SIZE) # mnist.train.next_batch(50)
  124. if i % 100 == 0:
  125. train_accuracy = accuracy.eval(feed_dict={
  126. x: batch[0], y_: batch[1], keep_prob: 1.0})
  127. print('step %d, training accuracy %g' % (i, train_accuracy))
  128. train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
  129. if __name__ == '__main__':
  130. parser = argparse.ArgumentParser()
  131. parser.add_argument('--data_dir', type=str,
  132. default='/tmp/tensorflow/mnist/input_data',
  133. help='Directory for storing input data')
  134. FLAGS, unparsed = parser.parse_known_args()
  135. tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)