decoder.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Basic CTC+recoder decoder.
  16. Decodes a sequence of class-ids into UTF-8 text.
  17. For basic information on CTC See:
  18. Alex Graves et al. Connectionist Temporal Classification: Labelling Unsegmented
  19. Sequence Data with Recurrent Neural Networks.
  20. http://www.cs.toronto.edu/~graves/icml_2006.pdf
  21. """
  22. import collections
  23. import re
  24. import errorcounter as ec
  25. import tensorflow as tf
  26. # Named tuple Part describes a part of a multi (1 or more) part code that
  27. # represents a utf-8 string. For example, Chinese character 'x' might be
  28. # represented by 3 codes of which (utf8='x', index=1, num_codes3) would be the
  29. # middle part. (The actual code is not stored in the tuple).
  30. Part = collections.namedtuple('Part', 'utf8 index, num_codes')
  31. # Class that decodes a sequence of class-ids into UTF-8 text.
  32. class Decoder(object):
  33. """Basic CTC+recoder decoder."""
  34. def __init__(self, filename):
  35. r"""Constructs a Decoder.
  36. Reads the text file describing the encoding and build the encoder.
  37. The text file contains lines of the form:
  38. <code>[,<code>]*\t<string>
  39. Each line defines a mapping from a sequence of one or more integer codes to
  40. a corresponding utf-8 string.
  41. Args:
  42. filename: Name of file defining the decoding sequences.
  43. """
  44. # self.decoder is a list of lists of Part(utf8, index, num_codes).
  45. # The index to the top-level list is a code. The list given by the code
  46. # index is a list of the parts represented by that code, Eg if the code 42
  47. # represents the 2nd (index 1) out of 3 part of Chinese character 'x', then
  48. # self.decoder[42] = [..., (utf8='x', index=1, num_codes3), ...] where ...
  49. # means all other uses of the code 42.
  50. self.decoder = []
  51. if filename:
  52. self._InitializeDecoder(filename)
  53. def SoftmaxEval(self, sess, model, num_steps):
  54. """Evaluate a model in softmax mode.
  55. Adds char, word recall and sequence error rate events to the sw summary
  56. writer, and returns them as well
  57. TODO(rays) Add LogisticEval.
  58. Args:
  59. sess: A tensor flow Session.
  60. model: The model to run in the session. Requires a VGSLImageModel or any
  61. other class that has a using_ctc attribute and a RunAStep(sess) method
  62. that reurns a softmax result with corresponding labels.
  63. num_steps: Number of steps to evaluate for.
  64. Returns:
  65. ErrorRates named tuple.
  66. Raises:
  67. ValueError: If an unsupported number of dimensions is used.
  68. """
  69. coord = tf.train.Coordinator()
  70. threads = tf.train.start_queue_runners(sess=sess, coord=coord)
  71. # Run the requested number of evaluation steps, gathering the outputs of the
  72. # softmax and the true labels of the evaluation examples.
  73. total_label_counts = ec.ErrorCounts(0, 0, 0, 0)
  74. total_word_counts = ec.ErrorCounts(0, 0, 0, 0)
  75. sequence_errors = 0
  76. for _ in xrange(num_steps):
  77. softmax_result, labels = model.RunAStep(sess)
  78. # Collapse softmax to same shape as labels.
  79. predictions = softmax_result.argmax(axis=-1)
  80. # Exclude batch from num_dims.
  81. num_dims = len(predictions.shape) - 1
  82. batch_size = predictions.shape[0]
  83. null_label = softmax_result.shape[-1] - 1
  84. for b in xrange(batch_size):
  85. if num_dims == 2:
  86. # TODO(rays) Support 2-d data.
  87. raise ValueError('2-d label data not supported yet!')
  88. else:
  89. if num_dims == 1:
  90. pred_batch = predictions[b, :]
  91. labels_batch = labels[b, :]
  92. else:
  93. pred_batch = [predictions[b]]
  94. labels_batch = [labels[b]]
  95. text = self.StringFromCTC(pred_batch, model.using_ctc, null_label)
  96. truth = self.StringFromCTC(labels_batch, False, null_label)
  97. # Note that recall_errs is false negatives (fn) aka drops/deletions.
  98. # Actual recall would be 1-fn/truth_words.
  99. # Likewise precision_errs is false positives (fp) aka adds/insertions.
  100. # Actual precision would be 1-fp/ocr_words.
  101. total_word_counts = ec.AddErrors(total_word_counts,
  102. ec.CountWordErrors(text, truth))
  103. total_label_counts = ec.AddErrors(total_label_counts,
  104. ec.CountErrors(text, truth))
  105. if text != truth:
  106. sequence_errors += 1
  107. coord.request_stop()
  108. coord.join(threads)
  109. return ec.ComputeErrorRates(total_label_counts, total_word_counts,
  110. sequence_errors, num_steps * batch_size)
  111. def StringFromCTC(self, ctc_labels, merge_dups, null_label):
  112. """Decodes CTC output to a string.
  113. Extracts only sequences of codes that are allowed by self.decoder.
  114. Labels that make illegal code sequences are dropped.
  115. Note that, by its nature of taking only top choices, this is much weaker
  116. than a full-blown beam search that considers all the softmax outputs.
  117. For languages without many multi-code sequences, this doesn't make much
  118. difference, but for complex scripts the accuracy will be much lower.
  119. Args:
  120. ctc_labels: List of class labels including null characters to remove.
  121. merge_dups: If True, Duplicate labels will be merged
  122. null_label: Label value to ignore.
  123. Returns:
  124. Labels decoded to a string.
  125. """
  126. # Run regular ctc on the labels, extracting a list of codes.
  127. codes = self._CodesFromCTC(ctc_labels, merge_dups, null_label)
  128. length = len(codes)
  129. if length == 0:
  130. return ''
  131. # strings and partials are both indexed by the same index as codes.
  132. # strings[i] is the best completed string upto position i, and
  133. # partials[i] is a list of partial code sequences at position i.
  134. # Warning: memory is squared-order in length.
  135. strings = []
  136. partials = []
  137. for pos in xrange(length):
  138. code = codes[pos]
  139. parts = self.decoder[code]
  140. partials.append([])
  141. strings.append('')
  142. # Iterate over the parts that this code can represent.
  143. for utf8, index, num_codes in parts:
  144. if index > pos:
  145. continue
  146. # We can use code if it is an initial code (index==0) or continues a
  147. # sequence in the partials list at the previous position.
  148. if index == 0 or partials[pos - 1].count(
  149. Part(utf8, index - 1, num_codes)) > 0:
  150. if index < num_codes - 1:
  151. # Save the partial sequence.
  152. partials[-1].append(Part(utf8, index, num_codes))
  153. elif not strings[-1]:
  154. # A code sequence is completed. Append to the best string that we
  155. # had where it started.
  156. if pos >= num_codes:
  157. strings[-1] = strings[pos - num_codes] + utf8
  158. else:
  159. strings[-1] = utf8
  160. if not strings[-1] and pos > 0:
  161. # We didn't get anything here so copy the previous best string, skipping
  162. # the current code, but it may just be a partial anyway.
  163. strings[-1] = strings[-2]
  164. return strings[-1]
  165. def _InitializeDecoder(self, filename):
  166. """Reads the decoder file and initializes self.decoder from it.
  167. Args:
  168. filename: Name of text file mapping codes to utf8 strings.
  169. Raises:
  170. ValueError: if the input file is not parsed correctly.
  171. """
  172. line_re = re.compile(r'(?P<codes>\d+(,\d+)*)\t(?P<utf8>.+)')
  173. with tf.gfile.GFile(filename) as f:
  174. for line in f:
  175. m = line_re.match(line)
  176. if m is None:
  177. raise ValueError('Unmatched line:', line)
  178. # codes is the sequence that maps to the string.
  179. str_codes = m.groupdict()['codes'].split(',')
  180. codes = []
  181. for code in str_codes:
  182. codes.append(int(code))
  183. utf8 = m.groupdict()['utf8']
  184. num_codes = len(codes)
  185. for index, code in enumerate(codes):
  186. while code >= len(self.decoder):
  187. self.decoder.append([])
  188. self.decoder[code].append(Part(utf8, index, num_codes))
  189. def _CodesFromCTC(self, ctc_labels, merge_dups, null_label):
  190. """Collapses CTC output to regular output.
  191. Args:
  192. ctc_labels: List of class labels including null characters to remove.
  193. merge_dups: If True, Duplicate labels will be merged.
  194. null_label: Label value to ignore.
  195. All trailing zeros are removed!!
  196. TODO(rays) This may become a problem with non-CTC models.
  197. If using charset, this should not be a problem as zero is always space.
  198. tf.pad can only append zero, so we have to be able to drop them, as a
  199. non-ctc will have learned to output trailing zeros instead of trailing
  200. nulls. This is awkward, as the stock ctc loss function requires that the
  201. null character be num_classes-1.
  202. Returns:
  203. (List of) Labels with null characters removed.
  204. """
  205. out_labels = []
  206. prev_label = -1
  207. zeros_needed = 0
  208. for label in ctc_labels:
  209. if label == null_label:
  210. prev_label = -1
  211. elif label != prev_label or not merge_dups:
  212. if label == 0:
  213. # Count zeros and only emit them when it is clear there is a non-zero
  214. # after, so as to truncate away all trailing zeros.
  215. zeros_needed += 1
  216. else:
  217. if merge_dups and zeros_needed > 0:
  218. out_labels.append(0)
  219. else:
  220. out_labels += [0] * zeros_needed
  221. zeros_needed = 0
  222. out_labels.append(label)
  223. prev_label = label
  224. return out_labels