tesseract  4.0.0-1-g2a2b
ctc.cpp
Go to the documentation of this file.
1 // File: ctc.cpp
3 // Description: Slightly improved standard CTC to compute the targets.
4 // Author: Ray Smith
5 // Created: Wed Jul 13 15:50:06 PDT 2016
6 //
7 // (C) Copyright 2016, Google Inc.
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
18 #include "ctc.h"
19 
20 #include <algorithm>
21 #include <cfloat> // for FLT_MAX
22 #include <memory>
23 
24 #include "genericvector.h"
25 #include "host.h"
26 #include "matrix.h"
27 #include "networkio.h"
28 
29 #include "network.h"
30 #include "scrollview.h"
31 
32 namespace tesseract {
33 
34 // Magic constants that keep CTC stable.
35 // Minimum probability limit for softmax input to ctc_loss.
36 const float CTC::kMinProb_ = 1e-12;
37 // Maximum absolute argument to exp().
38 const double CTC::kMaxExpArg_ = 80.0;
39 // Minimum probability for total prob in time normalization.
40 const double CTC::kMinTotalTimeProb_ = 1e-8;
41 // Minimum probability for total prob in final normalization.
42 const double CTC::kMinTotalFinalProb_ = 1e-6;
43 
44 // Builds a target using CTC. Slightly improved as follows:
45 // Includes normalizations and clipping for stability.
46 // labels should be pre-padded with nulls everywhere.
47 // labels can be longer than the time sequence, but the total number of
48 // essential labels (non-null plus nulls between equal labels) must not exceed
49 // the number of timesteps in outputs.
50 // outputs is the output of the network, and should have already been
51 // normalized with NormalizeProbs.
52 // On return targets is filled with the computed targets.
53 // Returns false if there is insufficient time for the labels.
54 /* static */
55 bool CTC::ComputeCTCTargets(const GenericVector<int>& labels, int null_char,
56  const GENERIC_2D_ARRAY<float>& outputs,
57  NetworkIO* targets) {
58  std::unique_ptr<CTC> ctc(new CTC(labels, null_char, outputs));
59  if (!ctc->ComputeLabelLimits()) {
60  return false; // Not enough time.
61  }
62  // Generate simple targets purely from the truth labels by spreading them
63  // evenly over time.
64  GENERIC_2D_ARRAY<float> simple_targets;
65  ctc->ComputeSimpleTargets(&simple_targets);
66  // Add the simple targets as a starter bias to the network outputs.
67  float bias_fraction = ctc->CalculateBiasFraction();
68  simple_targets *= bias_fraction;
69  ctc->outputs_ += simple_targets;
70  NormalizeProbs(&ctc->outputs_);
71  // Run regular CTC on the biased outputs.
72  // Run forward and backward
73  GENERIC_2D_ARRAY<double> log_alphas, log_betas;
74  ctc->Forward(&log_alphas);
75  ctc->Backward(&log_betas);
76  // Normalize and come out of log space with a clipped softmax over time.
77  log_alphas += log_betas;
78  ctc->NormalizeSequence(&log_alphas);
79  ctc->LabelsToClasses(log_alphas, targets);
80  NormalizeProbs(targets);
81  return true;
82 }
83 
84 CTC::CTC(const GenericVector<int>& labels, int null_char,
85  const GENERIC_2D_ARRAY<float>& outputs)
86  : labels_(labels), outputs_(outputs), null_char_(null_char) {
87  num_timesteps_ = outputs.dim1();
88  num_classes_ = outputs.dim2();
89  num_labels_ = labels_.size();
90 }
91 
92 // Computes vectors of min and max label index for each timestep, based on
93 // whether skippability of nulls makes it possible to complete a valid path.
94 bool CTC::ComputeLabelLimits() {
95  min_labels_.init_to_size(num_timesteps_, 0);
96  max_labels_.init_to_size(num_timesteps_, 0);
97  int min_u = num_labels_ - 1;
98  if (labels_[min_u] == null_char_) --min_u;
99  for (int t = num_timesteps_ - 1; t >= 0; --t) {
100  min_labels_[t] = min_u;
101  if (min_u > 0) {
102  --min_u;
103  if (labels_[min_u] == null_char_ && min_u > 0 &&
104  labels_[min_u + 1] != labels_[min_u - 1]) {
105  --min_u;
106  }
107  }
108  }
109  int max_u = labels_[0] == null_char_;
110  for (int t = 0; t < num_timesteps_; ++t) {
111  max_labels_[t] = max_u;
112  if (max_labels_[t] < min_labels_[t]) return false; // Not enough room.
113  if (max_u + 1 < num_labels_) {
114  ++max_u;
115  if (labels_[max_u] == null_char_ && max_u + 1 < num_labels_ &&
116  labels_[max_u + 1] != labels_[max_u - 1]) {
117  ++max_u;
118  }
119  }
120  }
121  return true;
122 }
123 
124 // Computes targets based purely on the labels by spreading the labels evenly
125 // over the available timesteps.
126 void CTC::ComputeSimpleTargets(GENERIC_2D_ARRAY<float>* targets) const {
127  // Initialize all targets to zero.
128  targets->Resize(num_timesteps_, num_classes_, 0.0f);
129  GenericVector<float> half_widths;
130  GenericVector<int> means;
131  ComputeWidthsAndMeans(&half_widths, &means);
132  for (int l = 0; l < num_labels_; ++l) {
133  int label = labels_[l];
134  float left_half_width = half_widths[l];
135  float right_half_width = left_half_width;
136  int mean = means[l];
137  if (label == null_char_) {
138  if (!NeededNull(l)) {
139  if ((l > 0 && mean == means[l - 1]) ||
140  (l + 1 < num_labels_ && mean == means[l + 1])) {
141  continue; // Drop overlapping null.
142  }
143  }
144  // Make sure that no space is left unoccupied and that non-nulls always
145  // peak at 1 by stretching nulls to meet their neighbors.
146  if (l > 0) left_half_width = mean - means[l - 1];
147  if (l + 1 < num_labels_) right_half_width = means[l + 1] - mean;
148  }
149  if (mean >= 0 && mean < num_timesteps_) targets->put(mean, label, 1.0f);
150  for (int offset = 1; offset < left_half_width && mean >= offset; ++offset) {
151  float prob = 1.0f - offset / left_half_width;
152  if (mean - offset < num_timesteps_ &&
153  prob > targets->get(mean - offset, label)) {
154  targets->put(mean - offset, label, prob);
155  }
156  }
157  for (int offset = 1;
158  offset < right_half_width && mean + offset < num_timesteps_;
159  ++offset) {
160  float prob = 1.0f - offset / right_half_width;
161  if (mean + offset >= 0 && prob > targets->get(mean + offset, label)) {
162  targets->put(mean + offset, label, prob);
163  }
164  }
165  }
166 }
167 
168 // Computes mean positions and half widths of the simple targets by spreading
169 // the labels evenly over the available timesteps.
170 void CTC::ComputeWidthsAndMeans(GenericVector<float>* half_widths,
171  GenericVector<int>* means) const {
172  // Count the number of labels of each type, in regexp terms, counts plus
173  // (non-null or necessary null, which must occur at least once) and star
174  // (optional null).
175  int num_plus = 0, num_star = 0;
176  for (int i = 0; i < num_labels_; ++i) {
177  if (labels_[i] != null_char_ || NeededNull(i))
178  ++num_plus;
179  else
180  ++num_star;
181  }
182  // Compute the size for each type. If there is enough space for everything
183  // to have size>=1, then all are equal, otherwise plus_size=1 and star gets
184  // whatever is left-over.
185  float plus_size = 1.0f, star_size = 0.0f;
186  float total_floating = num_plus + num_star;
187  if (total_floating <= num_timesteps_) {
188  plus_size = star_size = num_timesteps_ / total_floating;
189  } else if (num_star > 0) {
190  star_size = static_cast<float>(num_timesteps_ - num_plus) / num_star;
191  }
192  // Set the width and compute the mean of each.
193  float mean_pos = 0.0f;
194  for (int i = 0; i < num_labels_; ++i) {
195  float half_width;
196  if (labels_[i] != null_char_ || NeededNull(i)) {
197  half_width = plus_size / 2.0f;
198  } else {
199  half_width = star_size / 2.0f;
200  }
201  mean_pos += half_width;
202  means->push_back(static_cast<int>(mean_pos));
203  mean_pos += half_width;
204  half_widths->push_back(half_width);
205  }
206 }
207 
208 // Helper returns the index of the highest probability label at timestep t.
209 static int BestLabel(const GENERIC_2D_ARRAY<float>& outputs, int t) {
210  int result = 0;
211  int num_classes = outputs.dim2();
212  const float* outputs_t = outputs[t];
213  for (int c = 1; c < num_classes; ++c) {
214  if (outputs_t[c] > outputs_t[result]) result = c;
215  }
216  return result;
217 }
218 
219 // Calculates and returns a suitable fraction of the simple targets to add
220 // to the network outputs.
221 float CTC::CalculateBiasFraction() {
222  // Compute output labels via basic decoding.
223  GenericVector<int> output_labels;
224  for (int t = 0; t < num_timesteps_; ++t) {
225  int label = BestLabel(outputs_, t);
226  while (t + 1 < num_timesteps_ && BestLabel(outputs_, t + 1) == label) ++t;
227  if (label != null_char_) output_labels.push_back(label);
228  }
229  // Simple bag of labels error calculation.
230  GenericVector<int> truth_counts(num_classes_, 0);
231  GenericVector<int> output_counts(num_classes_, 0);
232  for (int l = 0; l < num_labels_; ++l) {
233  ++truth_counts[labels_[l]];
234  }
235  for (int l = 0; l < output_labels.size(); ++l) {
236  ++output_counts[output_labels[l]];
237  }
238  // Count the number of true and false positive non-nulls and truth labels.
239  int true_pos = 0, false_pos = 0, total_labels = 0;
240  for (int c = 0; c < num_classes_; ++c) {
241  if (c == null_char_) continue;
242  int truth_count = truth_counts[c];
243  int ocr_count = output_counts[c];
244  if (truth_count > 0) {
245  total_labels += truth_count;
246  if (ocr_count > truth_count) {
247  true_pos += truth_count;
248  false_pos += ocr_count - truth_count;
249  } else {
250  true_pos += ocr_count;
251  }
252  }
253  // We don't need to count classes that don't exist in the truth as
254  // false positives, because they don't affect CTC at all.
255  }
256  if (total_labels == 0) return 0.0f;
257  return exp(std::max(true_pos - false_pos, 1) * log(kMinProb_) / total_labels);
258 }
259 
260 // Given ln(x) and ln(y), returns ln(x + y), using:
261 // ln(x + y) = ln(y) + ln(1 + exp(ln(y) - ln(x)), ensuring that ln(x) is the
262 // bigger number to maximize precision.
263 static double LogSumExp(double ln_x, double ln_y) {
264  if (ln_x >= ln_y) {
265  return ln_x + log1p(exp(ln_y - ln_x));
266  } else {
267  return ln_y + log1p(exp(ln_x - ln_y));
268  }
269 }
270 
271 // Runs the forward CTC pass, filling in log_probs.
272 void CTC::Forward(GENERIC_2D_ARRAY<double>* log_probs) const {
273  log_probs->Resize(num_timesteps_, num_labels_, -FLT_MAX);
274  log_probs->put(0, 0, log(outputs_(0, labels_[0])));
275  if (labels_[0] == null_char_)
276  log_probs->put(0, 1, log(outputs_(0, labels_[1])));
277  for (int t = 1; t < num_timesteps_; ++t) {
278  const float* outputs_t = outputs_[t];
279  for (int u = min_labels_[t]; u <= max_labels_[t]; ++u) {
280  // Continuing the same label.
281  double log_sum = log_probs->get(t - 1, u);
282  // Change from previous label.
283  if (u > 0) {
284  log_sum = LogSumExp(log_sum, log_probs->get(t - 1, u - 1));
285  }
286  // Skip the null if allowed.
287  if (u >= 2 && labels_[u - 1] == null_char_ &&
288  labels_[u] != labels_[u - 2]) {
289  log_sum = LogSumExp(log_sum, log_probs->get(t - 1, u - 2));
290  }
291  // Add in the log prob of the current label.
292  double label_prob = outputs_t[labels_[u]];
293  log_sum += log(label_prob);
294  log_probs->put(t, u, log_sum);
295  }
296  }
297 }
298 
299 // Runs the backward CTC pass, filling in log_probs.
300 void CTC::Backward(GENERIC_2D_ARRAY<double>* log_probs) const {
301  log_probs->Resize(num_timesteps_, num_labels_, -FLT_MAX);
302  log_probs->put(num_timesteps_ - 1, num_labels_ - 1, 0.0);
303  if (labels_[num_labels_ - 1] == null_char_)
304  log_probs->put(num_timesteps_ - 1, num_labels_ - 2, 0.0);
305  for (int t = num_timesteps_ - 2; t >= 0; --t) {
306  const float* outputs_tp1 = outputs_[t + 1];
307  for (int u = min_labels_[t]; u <= max_labels_[t]; ++u) {
308  // Continuing the same label.
309  double log_sum = log_probs->get(t + 1, u) + log(outputs_tp1[labels_[u]]);
310  // Change from previous label.
311  if (u + 1 < num_labels_) {
312  double prev_prob = outputs_tp1[labels_[u + 1]];
313  log_sum =
314  LogSumExp(log_sum, log_probs->get(t + 1, u + 1) + log(prev_prob));
315  }
316  // Skip the null if allowed.
317  if (u + 2 < num_labels_ && labels_[u + 1] == null_char_ &&
318  labels_[u] != labels_[u + 2]) {
319  double skip_prob = outputs_tp1[labels_[u + 2]];
320  log_sum =
321  LogSumExp(log_sum, log_probs->get(t + 1, u + 2) + log(skip_prob));
322  }
323  log_probs->put(t, u, log_sum);
324  }
325  }
326 }
327 
328 // Normalizes and brings probs out of log space with a softmax over time.
329 void CTC::NormalizeSequence(GENERIC_2D_ARRAY<double>* probs) const {
330  double max_logprob = probs->Max();
331  for (int u = 0; u < num_labels_; ++u) {
332  double total = 0.0;
333  for (int t = 0; t < num_timesteps_; ++t) {
334  // Separate impossible path from unlikely probs.
335  double prob = probs->get(t, u);
336  if (prob > -FLT_MAX)
337  prob = ClippedExp(prob - max_logprob);
338  else
339  prob = 0.0;
340  total += prob;
341  probs->put(t, u, prob);
342  }
343  // Note that although this is a probability distribution over time and
344  // therefore should sum to 1, it is important to allow some labels to be
345  // all zero, (or at least tiny) as it is necessary to skip some blanks.
346  if (total < kMinTotalTimeProb_) total = kMinTotalTimeProb_;
347  for (int t = 0; t < num_timesteps_; ++t)
348  probs->put(t, u, probs->get(t, u) / total);
349  }
350 }
351 
352 // For each timestep computes the max prob for each class over all
353 // instances of the class in the labels_, and sets the targets to
354 // the max observed prob.
355 void CTC::LabelsToClasses(const GENERIC_2D_ARRAY<double>& probs,
356  NetworkIO* targets) const {
357  // For each timestep compute the max prob for each class over all
358  // instances of the class in the labels_.
359  GenericVector<double> class_probs;
360  for (int t = 0; t < num_timesteps_; ++t) {
361  float* targets_t = targets->f(t);
362  class_probs.init_to_size(num_classes_, 0.0);
363  for (int u = 0; u < num_labels_; ++u) {
364  double prob = probs(t, u);
365  // Note that although Graves specifies sum over all labels of the same
366  // class, we need to allow skipped blanks to go to zero, so they don't
367  // interfere with the non-blanks, so max is better than sum.
368  if (prob > class_probs[labels_[u]]) class_probs[labels_[u]] = prob;
369  // class_probs[labels_[u]] += prob;
370  }
371  int best_class = 0;
372  for (int c = 0; c < num_classes_; ++c) {
373  targets_t[c] = class_probs[c];
374  if (class_probs[c] > class_probs[best_class]) best_class = c;
375  }
376  }
377 }
378 
379 // Normalizes the probabilities such that no target has a prob below min_prob,
380 // and, provided that the initial total is at least min_total_prob, then all
381 // probs will sum to 1, otherwise to sum/min_total_prob. The maximum output
382 // probability is thus 1 - (num_classes-1)*min_prob.
383 /* static */
385  int num_timesteps = probs->dim1();
386  int num_classes = probs->dim2();
387  for (int t = 0; t < num_timesteps; ++t) {
388  float* probs_t = (*probs)[t];
389  // Compute the total and clip that to prevent amplification of noise.
390  double total = 0.0;
391  for (int c = 0; c < num_classes; ++c) total += probs_t[c];
392  if (total < kMinTotalFinalProb_) total = kMinTotalFinalProb_;
393  // Compute the increased total as a result of clipping.
394  double increment = 0.0;
395  for (int c = 0; c < num_classes; ++c) {
396  double prob = probs_t[c] / total;
397  if (prob < kMinProb_) increment += kMinProb_ - prob;
398  }
399  // Now normalize with clipping. Any additional clipping is negligible.
400  total += increment;
401  for (int c = 0; c < num_classes; ++c) {
402  float prob = probs_t[c] / total;
403  probs_t[c] = std::max(prob, kMinProb_);
404  }
405  }
406 }
407 
408 // Returns true if the label at index is a needed null.
409 bool CTC::NeededNull(int index) const {
410  return labels_[index] == null_char_ && index > 0 && index + 1 < num_labels_ &&
411  labels_[index + 1] == labels_[index - 1];
412 }
413 
414 } // namespace tesseract
int size() const
Definition: genericvector.h:71
static void NormalizeProbs(NetworkIO *probs)
Definition: ctc.h:36
static bool ComputeCTCTargets(const GenericVector< int > &truth_labels, int null_char, const GENERIC_2D_ARRAY< float > &outputs, NetworkIO *targets)
Definition: ctc.cpp:55
void init_to_size(int size, const T &t)
T Max() const
Definition: matrix.h:342
void put(ICOORD pos, const T &thing)
Definition: matrix.h:220
int push_back(T object)
int dim1() const
Definition: matrix.h:206
int dim2() const
Definition: matrix.h:207
void Resize(int size1, int size2, const T &empty)
Definition: matrix.h:105
T get(ICOORD pos) const
Definition: matrix.h:228