tesseract  4.00.00dev
lstmtrainer.cpp
Go to the documentation of this file.
1 // File: lstmtrainer.cpp
3 // Description: Top-level line trainer class for LSTM-based networks.
4 // Author: Ray Smith
5 // Created: Fir May 03 09:14:06 PST 2013
6 //
7 // (C) Copyright 2013, 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 
19 // Include automatically generated configuration file if running autoconf.
20 #ifdef HAVE_CONFIG_H
21 #include "config_auto.h"
22 #endif
23 
24 #include "lstmtrainer.h"
25 #include <string>
26 
27 #include "allheaders.h"
28 #include "boxread.h"
29 #include "ctc.h"
30 #include "imagedata.h"
31 #include "input.h"
32 #include "networkbuilder.h"
33 #include "ratngs.h"
34 #include "recodebeam.h"
35 #ifdef INCLUDE_TENSORFLOW
36 #include "tfnetwork.h"
37 #endif
38 #include "tprintf.h"
39 
40 #include "callcpp.h"
41 
42 namespace tesseract {
43 
44 // Min actual error rate increase to constitute divergence.
45 const double kMinDivergenceRate = 50.0;
46 // Min iterations since last best before acting on a stall.
47 const int kMinStallIterations = 10000;
48 // Fraction of current char error rate that sub_trainer_ has to be ahead
49 // before we declare the sub_trainer_ a success and switch to it.
50 const double kSubTrainerMarginFraction = 3.0 / 128;
51 // Factor to reduce learning rate on divergence.
52 const double kLearningRateDecay = sqrt(0.5);
53 // LR adjustment iterations.
54 const int kNumAdjustmentIterations = 100;
55 // How often to add data to the error_graph_.
56 const int kErrorGraphInterval = 1000;
57 // Number of training images to train between calls to MaintainCheckpoints.
58 const int kNumPagesPerBatch = 100;
59 // Min percent error rate to consider start-up phase over.
60 const int kMinStartedErrorRate = 75;
61 // Error rate at which to transition to stage 1.
62 const double kStageTransitionThreshold = 10.0;
63 // Confidence beyond which the truth is more likely wrong than the recognizer.
64 const double kHighConfidence = 0.9375; // 15/16.
65 // Fraction of weight sign-changing total to constitute a definite improvement.
66 const double kImprovementFraction = 15.0 / 16.0;
67 // Fraction of last written best to make it worth writing another.
68 const double kBestCheckpointFraction = 31.0 / 32.0;
69 // Scale factor for display of target activations of CTC.
70 const int kTargetXScale = 5;
71 const int kTargetYScale = 100;
72 
74  : randomly_rotate_(false),
75  training_data_(0),
76  file_reader_(LoadDataFromFile),
77  file_writer_(SaveDataToFile),
78  checkpoint_reader_(
79  NewPermanentTessCallback(this, &LSTMTrainer::ReadTrainingDump)),
80  checkpoint_writer_(
81  NewPermanentTessCallback(this, &LSTMTrainer::SaveTrainingDump)),
82  sub_trainer_(NULL) {
84  debug_interval_ = 0;
85 }
86 
88  CheckPointReader checkpoint_reader,
89  CheckPointWriter checkpoint_writer,
90  const char* model_base, const char* checkpoint_name,
91  int debug_interval, inT64 max_memory)
92  : randomly_rotate_(false),
93  training_data_(max_memory),
94  file_reader_(file_reader),
95  file_writer_(file_writer),
96  checkpoint_reader_(checkpoint_reader),
97  checkpoint_writer_(checkpoint_writer),
98  sub_trainer_(NULL),
99  mgr_(file_reader) {
103  if (checkpoint_reader_ == NULL) {
106  }
107  if (checkpoint_writer_ == NULL) {
110  }
111  debug_interval_ = debug_interval;
112  model_base_ = model_base;
113  checkpoint_name_ = checkpoint_name;
114 }
115 
117  delete align_win_;
118  delete target_win_;
119  delete ctc_win_;
120  delete recon_win_;
121  delete checkpoint_reader_;
122  delete checkpoint_writer_;
123  delete sub_trainer_;
124 }
125 
126 // Tries to deserialize a trainer from the given file and silently returns
127 // false in case of failure.
129  const char* old_traineddata) {
130  GenericVector<char> data;
131  if (!(*file_reader_)(filename, &data)) return false;
132  tprintf("Loaded file %s, unpacking...\n", filename);
133  if (!checkpoint_reader_->Run(data, this)) return false;
135  if (((old_traineddata == nullptr || *old_traineddata == '\0') &&
137  filename == old_traineddata) {
138  return true; // Normal checkpoint load complete.
139  }
140  tprintf("Code range changed from %d to %d!\n", network_->NumOutputs(),
141  recoder_.code_range());
142  if (old_traineddata == nullptr || *old_traineddata == '\0') {
143  tprintf("Must supply the old traineddata for code conversion!\n");
144  return false;
145  }
146  TessdataManager old_mgr;
147  ASSERT_HOST(old_mgr.Init(old_traineddata));
148  TFile fp;
149  if (!old_mgr.GetComponent(TESSDATA_LSTM_UNICHARSET, &fp)) return false;
150  UNICHARSET old_chset;
151  if (!old_chset.load_from_file(&fp, false)) return false;
152  if (!old_mgr.GetComponent(TESSDATA_LSTM_RECODER, &fp)) return false;
153  UnicharCompress old_recoder;
154  if (!old_recoder.DeSerialize(&fp)) return false;
155  std::vector<int> code_map = MapRecoder(old_chset, old_recoder);
156  // Set the null_char_ to the new value.
157  int old_null_char = null_char_;
158  SetNullChar();
159  // Map the softmax(s) in the network.
160  network_->RemapOutputs(old_recoder.code_range(), code_map);
161  tprintf("Previous null char=%d mapped to %d\n", old_null_char, null_char_);
162  return true;
163 }
164 
165 // Initializes the trainer with a network_spec in the network description
166 // net_flags control network behavior according to the NetworkFlags enum.
167 // There isn't really much difference between them - only where the effects
168 // are implemented.
169 // For other args see NetworkBuilder::InitNetwork.
170 // Note: Be sure to call InitCharSet before InitNetwork!
171 bool LSTMTrainer::InitNetwork(const STRING& network_spec, int append_index,
172  int net_flags, float weight_range,
173  float learning_rate, float momentum,
174  float adam_beta) {
175  mgr_.SetVersionString(mgr_.VersionString() + ":" + network_spec.string());
176  adam_beta_ = adam_beta;
178  momentum_ = momentum;
179  SetNullChar();
180  if (!NetworkBuilder::InitNetwork(recoder_.code_range(), network_spec,
181  append_index, net_flags, weight_range,
182  &randomizer_, &network_)) {
183  return false;
184  }
185  network_str_ += network_spec;
186  tprintf("Built network:%s from request %s\n",
187  network_->spec().string(), network_spec.string());
188  tprintf(
189  "Training parameters:\n Debug interval = %d,"
190  " weights = %g, learning rate = %g, momentum=%g\n",
191  debug_interval_, weight_range, learning_rate_, momentum_);
192  tprintf("null char=%d\n", null_char_);
193  return true;
194 }
195 
196 // Initializes a trainer from a serialized TFNetworkModel proto.
197 // Returns the global step of TensorFlow graph or 0 if failed.
198 int LSTMTrainer::InitTensorFlowNetwork(const std::string& tf_proto) {
199 #ifdef INCLUDE_TENSORFLOW
200  delete network_;
201  TFNetwork* tf_net = new TFNetwork("TensorFlow");
202  training_iteration_ = tf_net->InitFromProtoStr(tf_proto);
203  if (training_iteration_ == 0) {
204  tprintf("InitFromProtoStr failed!!\n");
205  return 0;
206  }
207  network_ = tf_net;
208  ASSERT_HOST(recoder_.code_range() == tf_net->num_classes());
209  return training_iteration_;
210 #else
211  tprintf("TensorFlow not compiled in! -DINCLUDE_TENSORFLOW\n");
212  return 0;
213 #endif
214 }
215 
216 // Resets all the iteration counters for fine tuning or traininng a head,
217 // where we want the error reporting to reset.
219  sample_iteration_ = 0;
223  best_error_rate_ = 100.0;
224  best_iteration_ = 0;
225  worst_error_rate_ = 0.0;
226  worst_iteration_ = 0;
229  perfect_delay_ = 0;
231  for (int i = 0; i < ET_COUNT; ++i) {
232  best_error_rates_[i] = 100.0;
233  worst_error_rates_[i] = 0.0;
235  error_rates_[i] = 100.0;
236  }
238 }
239 
240 // If the training sample is usable, grid searches for the optimal
241 // dict_ratio/cert_offset, and returns the results in a string of space-
242 // separated triplets of ratio,offset=worderr.
244  const ImageData* trainingdata, int iteration, double min_dict_ratio,
245  double dict_ratio_step, double max_dict_ratio, double min_cert_offset,
246  double cert_offset_step, double max_cert_offset, STRING* results) {
247  sample_iteration_ = iteration;
248  NetworkIO fwd_outputs, targets;
249  Trainability result =
250  PrepareForBackward(trainingdata, &fwd_outputs, &targets);
251  if (result == UNENCODABLE || result == HI_PRECISION_ERR || dict_ == NULL)
252  return result;
253 
254  // Encode/decode the truth to get the normalization.
255  GenericVector<int> truth_labels, ocr_labels, xcoords;
256  ASSERT_HOST(EncodeString(trainingdata->transcription(), &truth_labels));
257  // NO-dict error.
258  RecodeBeamSearch base_search(recoder_, null_char_, SimpleTextOutput(), NULL);
259  base_search.Decode(fwd_outputs, 1.0, 0.0, RecodeBeamSearch::kMinCertainty,
260  NULL);
261  base_search.ExtractBestPathAsLabels(&ocr_labels, &xcoords);
262  STRING truth_text = DecodeLabels(truth_labels);
263  STRING ocr_text = DecodeLabels(ocr_labels);
264  double baseline_error = ComputeWordError(&truth_text, &ocr_text);
265  results->add_str_double("0,0=", baseline_error);
266 
268  for (double r = min_dict_ratio; r < max_dict_ratio; r += dict_ratio_step) {
269  for (double c = min_cert_offset; c < max_cert_offset;
270  c += cert_offset_step) {
271  search.Decode(fwd_outputs, r, c, RecodeBeamSearch::kMinCertainty, NULL);
272  search.ExtractBestPathAsLabels(&ocr_labels, &xcoords);
273  truth_text = DecodeLabels(truth_labels);
274  ocr_text = DecodeLabels(ocr_labels);
275  // This is destructive on both strings.
276  double word_error = ComputeWordError(&truth_text, &ocr_text);
277  if ((r == min_dict_ratio && c == min_cert_offset) ||
278  !std::isfinite(word_error)) {
279  STRING t = DecodeLabels(truth_labels);
280  STRING o = DecodeLabels(ocr_labels);
281  tprintf("r=%g, c=%g, truth=%s, ocr=%s, wderr=%g, truth[0]=%d\n", r, c,
282  t.string(), o.string(), word_error, truth_labels[0]);
283  }
284  results->add_str_double(" ", r);
285  results->add_str_double(",", c);
286  results->add_str_double("=", word_error);
287  }
288  }
289  return result;
290 }
291 
292 // Provides output on the distribution of weight values.
295 }
296 
297 // Loads a set of lstmf files that were created using the lstm.train config to
298 // tesseract into memory ready for training. Returns false if nothing was
299 // loaded.
301  CachingStrategy cache_strategy,
302  bool randomly_rotate) {
303  randomly_rotate_ = randomly_rotate;
305  return training_data_.LoadDocuments(filenames, cache_strategy, file_reader_);
306 }
307 
308 // Keeps track of best and locally worst char error_rate and launches tests
309 // using tester, when a new min or max is reached.
310 // Writes checkpoints at appropriate times and builds and returns a log message
311 // to indicate progress. Returns false if nothing interesting happened.
313  PrepareLogMsg(log_msg);
314  double error_rate = CharError();
315  int iteration = learning_iteration();
316  if (iteration >= stall_iteration_ &&
317  error_rate > best_error_rate_ * (1.0 + kSubTrainerMarginFraction) &&
318  best_error_rate_ < kMinStartedErrorRate && !best_trainer_.empty()) {
319  // It hasn't got any better in a long while, and is a margin worse than the
320  // best, so go back to the best model and try a different learning rate.
321  StartSubtrainer(log_msg);
322  }
323  SubTrainerResult sub_trainer_result = STR_NONE;
324  if (sub_trainer_ != NULL) {
325  sub_trainer_result = UpdateSubtrainer(log_msg);
326  if (sub_trainer_result == STR_REPLACED) {
327  // Reset the inputs, as we have overwritten *this.
328  error_rate = CharError();
329  iteration = learning_iteration();
330  PrepareLogMsg(log_msg);
331  }
332  }
333  bool result = true; // Something interesting happened.
334  GenericVector<char> rec_model_data;
335  if (error_rate < best_error_rate_) {
336  SaveRecognitionDump(&rec_model_data);
337  log_msg->add_str_double(" New best char error = ", error_rate);
338  *log_msg += UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
339  // If sub_trainer_ is not NULL, either *this beat it to a new best, or it
340  // just overwrote *this. In either case, we have finished with it.
341  delete sub_trainer_;
342  sub_trainer_ = NULL;
344  if (TransitionTrainingStage(kStageTransitionThreshold)) {
345  log_msg->add_str_int(" Transitioned to stage ", CurrentTrainingStage());
346  }
348  if (error_rate < error_rate_of_last_saved_best_ * kBestCheckpointFraction) {
349  STRING best_model_name = DumpFilename();
350  if (!(*file_writer_)(best_trainer_, best_model_name)) {
351  *log_msg += " failed to write best model:";
352  } else {
353  *log_msg += " wrote best model:";
355  }
356  *log_msg += best_model_name;
357  }
358  } else if (error_rate > worst_error_rate_) {
359  SaveRecognitionDump(&rec_model_data);
360  log_msg->add_str_double(" New worst char error = ", error_rate);
361  *log_msg += UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
362  if (worst_error_rate_ > best_error_rate_ + kMinDivergenceRate &&
363  best_error_rate_ < kMinStartedErrorRate && !best_trainer_.empty()) {
364  // Error rate has ballooned. Go back to the best model.
365  *log_msg += "\nDivergence! ";
366  // Copy best_trainer_ before reading it, as it will get overwritten.
367  GenericVector<char> revert_data(best_trainer_);
368  if (checkpoint_reader_->Run(revert_data, this)) {
369  LogIterations("Reverted to", log_msg);
370  ReduceLearningRates(this, log_msg);
371  } else {
372  LogIterations("Failed to Revert at", log_msg);
373  }
374  // If it fails again, we will wait twice as long before reverting again.
375  stall_iteration_ = iteration + 2 * (iteration - learning_iteration());
376  // Re-save the best trainer with the new learning rates and stall
377  // iteration.
379  }
380  } else {
381  // Something interesting happened only if the sub_trainer_ was trained.
382  result = sub_trainer_result != STR_NONE;
383  }
384  if (checkpoint_writer_ != NULL && file_writer_ != NULL &&
385  checkpoint_name_.length() > 0) {
386  // Write a current checkpoint.
387  GenericVector<char> checkpoint;
388  if (!checkpoint_writer_->Run(FULL, this, &checkpoint) ||
389  !(*file_writer_)(checkpoint, checkpoint_name_)) {
390  *log_msg += " failed to write checkpoint.";
391  } else {
392  *log_msg += " wrote checkpoint.";
393  }
394  }
395  *log_msg += "\n";
396  return result;
397 }
398 
399 // Builds a string containing a progress message with current error rates.
400 void LSTMTrainer::PrepareLogMsg(STRING* log_msg) const {
401  LogIterations("At", log_msg);
402  log_msg->add_str_double(", Mean rms=", error_rates_[ET_RMS]);
403  log_msg->add_str_double("%, delta=", error_rates_[ET_DELTA]);
404  log_msg->add_str_double("%, char train=", error_rates_[ET_CHAR_ERROR]);
405  log_msg->add_str_double("%, word train=", error_rates_[ET_WORD_RECERR]);
406  log_msg->add_str_double("%, skip ratio=", error_rates_[ET_SKIP_RATIO]);
407  *log_msg += "%, ";
408 }
409 
410 // Appends <intro_str> iteration learning_iteration()/training_iteration()/
411 // sample_iteration() to the log_msg.
412 void LSTMTrainer::LogIterations(const char* intro_str, STRING* log_msg) const {
413  *log_msg += intro_str;
414  log_msg->add_str_int(" iteration ", learning_iteration());
415  log_msg->add_str_int("/", training_iteration());
416  log_msg->add_str_int("/", sample_iteration());
417 }
418 
419 // Returns true and increments the training_stage_ if the error rate has just
420 // passed through the given threshold for the first time.
421 bool LSTMTrainer::TransitionTrainingStage(float error_threshold) {
422  if (best_error_rate_ < error_threshold &&
424  ++training_stage_;
425  return true;
426  }
427  return false;
428 }
429 
430 // Writes to the given file. Returns false in case of error.
432  const TessdataManager* mgr, TFile* fp) const {
433  if (!LSTMRecognizer::Serialize(mgr, fp)) return false;
434  if (fp->FWrite(&learning_iteration_, sizeof(learning_iteration_), 1) != 1)
435  return false;
436  if (fp->FWrite(&prev_sample_iteration_, sizeof(prev_sample_iteration_), 1) !=
437  1)
438  return false;
439  if (fp->FWrite(&perfect_delay_, sizeof(perfect_delay_), 1) != 1) return false;
441  sizeof(last_perfect_training_iteration_), 1) != 1)
442  return false;
443  for (int i = 0; i < ET_COUNT; ++i) {
444  if (!error_buffers_[i].Serialize(fp)) return false;
445  }
446  if (fp->FWrite(&error_rates_, sizeof(error_rates_), 1) != 1) return false;
447  if (fp->FWrite(&training_stage_, sizeof(training_stage_), 1) != 1)
448  return false;
449  uinT8 amount = serialize_amount;
450  if (fp->FWrite(&amount, sizeof(amount), 1) != 1) return false;
451  if (serialize_amount == LIGHT) return true; // We are done.
452  if (fp->FWrite(&best_error_rate_, sizeof(best_error_rate_), 1) != 1)
453  return false;
454  if (fp->FWrite(&best_error_rates_, sizeof(best_error_rates_), 1) != 1)
455  return false;
456  if (fp->FWrite(&best_iteration_, sizeof(best_iteration_), 1) != 1)
457  return false;
458  if (fp->FWrite(&worst_error_rate_, sizeof(worst_error_rate_), 1) != 1)
459  return false;
460  if (fp->FWrite(&worst_error_rates_, sizeof(worst_error_rates_), 1) != 1)
461  return false;
462  if (fp->FWrite(&worst_iteration_, sizeof(worst_iteration_), 1) != 1)
463  return false;
464  if (fp->FWrite(&stall_iteration_, sizeof(stall_iteration_), 1) != 1)
465  return false;
466  if (!best_model_data_.Serialize(fp)) return false;
467  if (!worst_model_data_.Serialize(fp)) return false;
468  if (serialize_amount != NO_BEST_TRAINER && !best_trainer_.Serialize(fp))
469  return false;
470  GenericVector<char> sub_data;
471  if (sub_trainer_ != NULL && !SaveTrainingDump(LIGHT, sub_trainer_, &sub_data))
472  return false;
473  if (!sub_data.Serialize(fp)) return false;
474  if (!best_error_history_.Serialize(fp)) return false;
475  if (!best_error_iterations_.Serialize(fp)) return false;
476  if (fp->FWrite(&improvement_steps_, sizeof(improvement_steps_), 1) != 1)
477  return false;
478  return true;
479 }
480 
481 // Reads from the given file. Returns false in case of error.
482 // NOTE: It is assumed that the trainer is never read cross-endian.
484  if (!LSTMRecognizer::DeSerialize(mgr, fp)) return false;
485  if (fp->FRead(&learning_iteration_, sizeof(learning_iteration_), 1) != 1) {
486  // Special case. If we successfully decoded the recognizer, but fail here
487  // then it means we were just given a recognizer, so issue a warning and
488  // allow it.
489  tprintf("Warning: LSTMTrainer deserialized an LSTMRecognizer!\n");
492  return true;
493  }
495  1) != 1)
496  return false;
497  if (fp->FReadEndian(&perfect_delay_, sizeof(perfect_delay_), 1) != 1)
498  return false;
500  sizeof(last_perfect_training_iteration_), 1) != 1)
501  return false;
502  for (int i = 0; i < ET_COUNT; ++i) {
503  if (!error_buffers_[i].DeSerialize(fp)) return false;
504  }
505  if (fp->FRead(&error_rates_, sizeof(error_rates_), 1) != 1) return false;
506  if (fp->FReadEndian(&training_stage_, sizeof(training_stage_), 1) != 1)
507  return false;
508  uinT8 amount;
509  if (fp->FRead(&amount, sizeof(amount), 1) != 1) return false;
510  if (amount == LIGHT) return true; // Don't read the rest.
511  if (fp->FReadEndian(&best_error_rate_, sizeof(best_error_rate_), 1) != 1)
512  return false;
513  if (fp->FReadEndian(&best_error_rates_, sizeof(best_error_rates_), 1) != 1)
514  return false;
515  if (fp->FReadEndian(&best_iteration_, sizeof(best_iteration_), 1) != 1)
516  return false;
517  if (fp->FReadEndian(&worst_error_rate_, sizeof(worst_error_rate_), 1) != 1)
518  return false;
519  if (fp->FReadEndian(&worst_error_rates_, sizeof(worst_error_rates_), 1) != 1)
520  return false;
521  if (fp->FReadEndian(&worst_iteration_, sizeof(worst_iteration_), 1) != 1)
522  return false;
523  if (fp->FReadEndian(&stall_iteration_, sizeof(stall_iteration_), 1) != 1)
524  return false;
525  if (!best_model_data_.DeSerialize(fp)) return false;
526  if (!worst_model_data_.DeSerialize(fp)) return false;
527  if (amount != NO_BEST_TRAINER && !best_trainer_.DeSerialize(fp)) return false;
528  GenericVector<char> sub_data;
529  if (!sub_data.DeSerialize(fp)) return false;
530  delete sub_trainer_;
531  if (sub_data.empty()) {
532  sub_trainer_ = NULL;
533  } else {
534  sub_trainer_ = new LSTMTrainer();
535  if (!ReadTrainingDump(sub_data, sub_trainer_)) return false;
536  }
537  if (!best_error_history_.DeSerialize(fp)) return false;
538  if (!best_error_iterations_.DeSerialize(fp)) return false;
539  if (fp->FReadEndian(&improvement_steps_, sizeof(improvement_steps_), 1) != 1)
540  return false;
541  return true;
542 }
543 
544 // De-serializes the saved best_trainer_ into sub_trainer_, and adjusts the
545 // learning rates (by scaling reduction, or layer specific, according to
546 // NF_LAYER_SPECIFIC_LR).
548  delete sub_trainer_;
549  sub_trainer_ = new LSTMTrainer();
551  *log_msg += " Failed to revert to previous best for trial!";
552  delete sub_trainer_;
553  sub_trainer_ = NULL;
554  } else {
555  log_msg->add_str_int(" Trial sub_trainer_ from iteration ",
557  // Reduce learning rate so it doesn't diverge this time.
558  sub_trainer_->ReduceLearningRates(this, log_msg);
559  // If it fails again, we will wait twice as long before reverting again.
560  int stall_offset =
562  stall_iteration_ = learning_iteration() + 2 * stall_offset;
564  // Re-save the best trainer with the new learning rates and stall iteration.
566  }
567 }
568 
569 // While the sub_trainer_ is behind the current training iteration and its
570 // training error is at least kSubTrainerMarginFraction better than the
571 // current training error, trains the sub_trainer_, and returns STR_UPDATED if
572 // it did anything. If it catches up, and has a better error rate than the
573 // current best, as well as a margin over the current error rate, then the
574 // trainer in *this is replaced with sub_trainer_, and STR_REPLACED is
575 // returned. STR_NONE is returned if the subtrainer wasn't good enough to
576 // receive any training iterations.
578  double training_error = CharError();
579  double sub_error = sub_trainer_->CharError();
580  double sub_margin = (training_error - sub_error) / sub_error;
581  if (sub_margin >= kSubTrainerMarginFraction) {
582  log_msg->add_str_double(" sub_trainer=", sub_error);
583  log_msg->add_str_double(" margin=", 100.0 * sub_margin);
584  *log_msg += "\n";
585  // Catch up to current iteration.
586  int end_iteration = training_iteration();
587  while (sub_trainer_->training_iteration() < end_iteration &&
588  sub_margin >= kSubTrainerMarginFraction) {
589  int target_iteration =
591  while (sub_trainer_->training_iteration() < target_iteration) {
592  sub_trainer_->TrainOnLine(this, false);
593  }
594  STRING batch_log = "Sub:";
595  sub_trainer_->PrepareLogMsg(&batch_log);
596  batch_log += "\n";
597  tprintf("UpdateSubtrainer:%s", batch_log.string());
598  *log_msg += batch_log;
599  sub_error = sub_trainer_->CharError();
600  sub_margin = (training_error - sub_error) / sub_error;
601  }
602  if (sub_error < best_error_rate_ &&
603  sub_margin >= kSubTrainerMarginFraction) {
604  // The sub_trainer_ has won the race to a new best. Switch to it.
605  GenericVector<char> updated_trainer;
606  SaveTrainingDump(LIGHT, sub_trainer_, &updated_trainer);
607  ReadTrainingDump(updated_trainer, this);
608  log_msg->add_str_int(" Sub trainer wins at iteration ",
610  *log_msg += "\n";
611  return STR_REPLACED;
612  }
613  return STR_UPDATED;
614  }
615  return STR_NONE;
616 }
617 
618 // Reduces network learning rates, either for everything, or for layers
619 // independently, according to NF_LAYER_SPECIFIC_LR.
621  STRING* log_msg) {
623  int num_reduced = ReduceLayerLearningRates(
624  kLearningRateDecay, kNumAdjustmentIterations, samples_trainer);
625  log_msg->add_str_int("\nReduced learning rate on layers: ", num_reduced);
626  } else {
627  ScaleLearningRate(kLearningRateDecay);
628  log_msg->add_str_double("\nReduced learning rate to :", learning_rate_);
629  }
630  *log_msg += "\n";
631 }
632 
633 // Considers reducing the learning rate independently for each layer down by
634 // factor(<1), or leaving it the same, by double-training the given number of
635 // samples and minimizing the amount of changing of sign of weight updates.
636 // Even if it looks like all weights should remain the same, an adjustment
637 // will be made to guarantee a different result when reverting to an old best.
638 // Returns the number of layer learning rates that were reduced.
639 int LSTMTrainer::ReduceLayerLearningRates(double factor, int num_samples,
640  LSTMTrainer* samples_trainer) {
641  enum WhichWay {
642  LR_DOWN, // Learning rate will go down by factor.
643  LR_SAME, // Learning rate will stay the same.
644  LR_COUNT // Size of arrays.
645  };
647  int num_layers = layers.size();
648  GenericVector<int> num_weights;
649  num_weights.init_to_size(num_layers, 0);
650  GenericVector<double> bad_sums[LR_COUNT];
651  GenericVector<double> ok_sums[LR_COUNT];
652  for (int i = 0; i < LR_COUNT; ++i) {
653  bad_sums[i].init_to_size(num_layers, 0.0);
654  ok_sums[i].init_to_size(num_layers, 0.0);
655  }
656  double momentum_factor = 1.0 / (1.0 - momentum_);
657  GenericVector<char> orig_trainer;
658  samples_trainer->SaveTrainingDump(LIGHT, this, &orig_trainer);
659  for (int i = 0; i < num_layers; ++i) {
660  Network* layer = GetLayer(layers[i]);
661  num_weights[i] = layer->IsTraining() ? layer->num_weights() : 0;
662  }
663  int iteration = sample_iteration();
664  for (int s = 0; s < num_samples; ++s) {
665  // Which way will we modify the learning rate?
666  for (int ww = 0; ww < LR_COUNT; ++ww) {
667  // Transfer momentum to learning rate and adjust by the ww factor.
668  float ww_factor = momentum_factor;
669  if (ww == LR_DOWN) ww_factor *= factor;
670  // Make a copy of *this, so we can mess about without damaging anything.
671  LSTMTrainer copy_trainer;
672  samples_trainer->ReadTrainingDump(orig_trainer, &copy_trainer);
673  // Clear the updates, doing nothing else.
674  copy_trainer.network_->Update(0.0, 0.0, 0.0, 0);
675  // Adjust the learning rate in each layer.
676  for (int i = 0; i < num_layers; ++i) {
677  if (num_weights[i] == 0) continue;
678  copy_trainer.ScaleLayerLearningRate(layers[i], ww_factor);
679  }
680  copy_trainer.SetIteration(iteration);
681  // Train on the sample, but keep the update in updates_ instead of
682  // applying to the weights.
683  const ImageData* trainingdata =
684  copy_trainer.TrainOnLine(samples_trainer, true);
685  if (trainingdata == NULL) continue;
686  // We'll now use this trainer again for each layer.
687  GenericVector<char> updated_trainer;
688  samples_trainer->SaveTrainingDump(LIGHT, &copy_trainer, &updated_trainer);
689  for (int i = 0; i < num_layers; ++i) {
690  if (num_weights[i] == 0) continue;
691  LSTMTrainer layer_trainer;
692  samples_trainer->ReadTrainingDump(updated_trainer, &layer_trainer);
693  Network* layer = layer_trainer.GetLayer(layers[i]);
694  // Update the weights in just the layer, using Adam if enabled.
695  layer->Update(0.0, momentum_, adam_beta_,
696  layer_trainer.training_iteration_ + 1);
697  // Zero the updates matrix again.
698  layer->Update(0.0, 0.0, 0.0, 0);
699  // Train again on the same sample, again holding back the updates.
700  layer_trainer.TrainOnLine(trainingdata, true);
701  // Count the sign changes in the updates in layer vs in copy_trainer.
702  float before_bad = bad_sums[ww][i];
703  float before_ok = ok_sums[ww][i];
704  layer->CountAlternators(*copy_trainer.GetLayer(layers[i]),
705  &ok_sums[ww][i], &bad_sums[ww][i]);
706  float bad_frac =
707  bad_sums[ww][i] + ok_sums[ww][i] - before_bad - before_ok;
708  if (bad_frac > 0.0f)
709  bad_frac = (bad_sums[ww][i] - before_bad) / bad_frac;
710  }
711  }
712  ++iteration;
713  }
714  int num_lowered = 0;
715  for (int i = 0; i < num_layers; ++i) {
716  if (num_weights[i] == 0) continue;
717  Network* layer = GetLayer(layers[i]);
718  float lr = GetLayerLearningRate(layers[i]);
719  double total_down = bad_sums[LR_DOWN][i] + ok_sums[LR_DOWN][i];
720  double total_same = bad_sums[LR_SAME][i] + ok_sums[LR_SAME][i];
721  double frac_down = bad_sums[LR_DOWN][i] / total_down;
722  double frac_same = bad_sums[LR_SAME][i] / total_same;
723  tprintf("Layer %d=%s: lr %g->%g%%, lr %g->%g%%", i, layer->name().string(),
724  lr * factor, 100.0 * frac_down, lr, 100.0 * frac_same);
725  if (frac_down < frac_same * kImprovementFraction) {
726  tprintf(" REDUCED\n");
727  ScaleLayerLearningRate(layers[i], factor);
728  ++num_lowered;
729  } else {
730  tprintf(" SAME\n");
731  }
732  }
733  if (num_lowered == 0) {
734  // Just lower everything to make sure.
735  for (int i = 0; i < num_layers; ++i) {
736  if (num_weights[i] > 0) {
737  ScaleLayerLearningRate(layers[i], factor);
738  ++num_lowered;
739  }
740  }
741  }
742  return num_lowered;
743 }
744 
745 // Converts the string to integer class labels, with appropriate null_char_s
746 // in between if not in SimpleTextOutput mode. Returns false on failure.
747 /* static */
748 bool LSTMTrainer::EncodeString(const STRING& str, const UNICHARSET& unicharset,
749  const UnicharCompress* recoder, bool simple_text,
750  int null_char, GenericVector<int>* labels) {
751  if (str.string() == NULL || str.length() <= 0) {
752  tprintf("Empty truth string!\n");
753  return false;
754  }
755  int err_index;
756  GenericVector<int> internal_labels;
757  labels->truncate(0);
758  if (!simple_text) labels->push_back(null_char);
759  string cleaned = unicharset.CleanupString(str.string());
760  if (unicharset.encode_string(cleaned.c_str(), true, &internal_labels, NULL,
761  &err_index)) {
762  bool success = true;
763  for (int i = 0; i < internal_labels.size(); ++i) {
764  if (recoder != NULL) {
765  // Re-encode labels via recoder.
766  RecodedCharID code;
767  int len = recoder->EncodeUnichar(internal_labels[i], &code);
768  if (len > 0) {
769  for (int j = 0; j < len; ++j) {
770  labels->push_back(code(j));
771  if (!simple_text) labels->push_back(null_char);
772  }
773  } else {
774  success = false;
775  err_index = 0;
776  break;
777  }
778  } else {
779  labels->push_back(internal_labels[i]);
780  if (!simple_text) labels->push_back(null_char);
781  }
782  }
783  if (success) return true;
784  }
785  tprintf("Encoding of string failed! Failure bytes:");
786  while (err_index < cleaned.size()) {
787  tprintf(" %x", cleaned[err_index++]);
788  }
789  tprintf("\n");
790  return false;
791 }
792 
793 // Performs forward-backward on the given trainingdata.
794 // Returns a Trainability enum to indicate the suitability of the sample.
796  bool batch) {
797  NetworkIO fwd_outputs, targets;
798  Trainability trainable =
799  PrepareForBackward(trainingdata, &fwd_outputs, &targets);
801  if (trainable == UNENCODABLE || trainable == NOT_BOXED) {
802  return trainable; // Sample was unusable.
803  }
804  bool debug = debug_interval_ > 0 &&
806  // Run backprop on the output.
807  NetworkIO bp_deltas;
808  if (network_->IsTraining() &&
809  (trainable != PERFECT ||
812  network_->Backward(debug, targets, &scratch_space_, &bp_deltas);
814  training_iteration_ + 1);
815  }
816 #ifndef GRAPHICS_DISABLED
817  if (debug_interval_ == 1 && debug_win_ != NULL) {
819  }
820 #endif // GRAPHICS_DISABLED
821  // Roll the memory of past means.
823  return trainable;
824 }
825 
826 // Prepares the ground truth, runs forward, and prepares the targets.
827 // Returns a Trainability enum to indicate the suitability of the sample.
829  NetworkIO* fwd_outputs,
830  NetworkIO* targets) {
831  if (trainingdata == NULL) {
832  tprintf("Null trainingdata.\n");
833  return UNENCODABLE;
834  }
835  // Ensure repeatability of random elements even across checkpoints.
836  bool debug = debug_interval_ > 0 &&
838  GenericVector<int> truth_labels;
839  if (!EncodeString(trainingdata->transcription(), &truth_labels)) {
840  tprintf("Can't encode transcription: '%s' in language '%s'\n",
841  trainingdata->transcription().string(),
842  trainingdata->language().string());
843  return UNENCODABLE;
844  }
845  bool upside_down = false;
846  if (randomly_rotate_) {
847  // This ensures consistent training results.
848  SetRandomSeed();
849  upside_down = randomizer_.SignedRand(1.0) > 0.0;
850  if (upside_down) {
851  // Modify the truth labels to match the rotation:
852  // Apart from space and null, increment the label. This is changes the
853  // script-id to the same script-id but upside-down.
854  // The labels need to be reversed in order, as the first is now the last.
855  for (int c = 0; c < truth_labels.size(); ++c) {
856  if (truth_labels[c] != UNICHAR_SPACE && truth_labels[c] != null_char_)
857  ++truth_labels[c];
858  }
859  truth_labels.reverse();
860  }
861  }
862  int w = 0;
863  while (w < truth_labels.size() &&
864  (truth_labels[w] == UNICHAR_SPACE || truth_labels[w] == null_char_))
865  ++w;
866  if (w == truth_labels.size()) {
867  tprintf("Blank transcription: %s\n",
868  trainingdata->transcription().string());
869  return UNENCODABLE;
870  }
871  float image_scale;
872  NetworkIO inputs;
873  bool invert = trainingdata->boxes().empty();
874  if (!RecognizeLine(*trainingdata, invert, debug, invert, upside_down,
875  &image_scale, &inputs, fwd_outputs)) {
876  tprintf("Image not trainable\n");
877  return UNENCODABLE;
878  }
879  targets->Resize(*fwd_outputs, network_->NumOutputs());
880  LossType loss_type = OutputLossType();
881  if (loss_type == LT_SOFTMAX) {
882  if (!ComputeTextTargets(*fwd_outputs, truth_labels, targets)) {
883  tprintf("Compute simple targets failed!\n");
884  return UNENCODABLE;
885  }
886  } else if (loss_type == LT_CTC) {
887  if (!ComputeCTCTargets(truth_labels, fwd_outputs, targets)) {
888  tprintf("Compute CTC targets failed!\n");
889  return UNENCODABLE;
890  }
891  } else {
892  tprintf("Logistic outputs not implemented yet!\n");
893  return UNENCODABLE;
894  }
895  GenericVector<int> ocr_labels;
896  GenericVector<int> xcoords;
897  LabelsFromOutputs(*fwd_outputs, &ocr_labels, &xcoords);
898  // CTC does not produce correct target labels to begin with.
899  if (loss_type != LT_CTC) {
900  LabelsFromOutputs(*targets, &truth_labels, &xcoords);
901  }
902  if (!DebugLSTMTraining(inputs, *trainingdata, *fwd_outputs, truth_labels,
903  *targets)) {
904  tprintf("Input width was %d\n", inputs.Width());
905  return UNENCODABLE;
906  }
907  STRING ocr_text = DecodeLabels(ocr_labels);
908  STRING truth_text = DecodeLabels(truth_labels);
909  targets->SubtractAllFromFloat(*fwd_outputs);
910  if (debug_interval_ != 0) {
911  tprintf("Iteration %d: BEST OCR TEXT : %s\n", training_iteration(),
912  ocr_text.string());
913  }
914  double char_error = ComputeCharError(truth_labels, ocr_labels);
915  double word_error = ComputeWordError(&truth_text, &ocr_text);
916  double delta_error = ComputeErrorRates(*targets, char_error, word_error);
917  if (debug_interval_ != 0) {
918  tprintf("File %s page %d %s:\n", trainingdata->imagefilename().string(),
919  trainingdata->page_number(), delta_error == 0.0 ? "(Perfect)" : "");
920  }
921  if (delta_error == 0.0) return PERFECT;
922  if (targets->AnySuspiciousTruth(kHighConfidence)) return HI_PRECISION_ERR;
923  return TRAINABLE;
924 }
925 
926 // Writes the trainer to memory, so that the current training state can be
927 // restored. *this must always be the master trainer that retains the only
928 // copy of the training data and language model. trainer is the model that is
929 // actually serialized.
931  const LSTMTrainer* trainer,
932  GenericVector<char>* data) const {
933  TFile fp;
934  fp.OpenWrite(data);
935  return trainer->Serialize(serialize_amount, &mgr_, &fp);
936 }
937 
938 // Restores the model to *this.
940  const char* data, int size) {
941  if (size == 0) {
942  tprintf("Warning: data size is 0 in LSTMTrainer::ReadLocalTrainingDump\n");
943  return false;
944  }
945  TFile fp;
946  fp.Open(data, size);
947  return DeSerialize(mgr, &fp);
948 }
949 
950 // Writes the full recognition traineddata to the given filename.
952  GenericVector<char> recognizer_data;
953  SaveRecognitionDump(&recognizer_data);
954  mgr_.OverwriteEntry(TESSDATA_LSTM, &recognizer_data[0],
955  recognizer_data.size());
956  return mgr_.SaveFile(filename, file_writer_);
957 }
958 
959 // Writes the recognizer to memory, so that it can be used for testing later.
961  TFile fp;
962  fp.OpenWrite(data);
966 }
967 
968 // Returns a suitable filename for a training dump, based on the model_base_,
969 // the iteration and the error rates.
973  filename.add_str_int("_", best_iteration_);
974  filename += ".checkpoint";
975  return filename;
976 }
977 
978 // Fills the whole error buffer of the given type with the given value.
979 void LSTMTrainer::FillErrorBuffer(double new_error, ErrorTypes type) {
980  for (int i = 0; i < kRollingBufferSize_; ++i)
981  error_buffers_[type][i] = new_error;
982  error_rates_[type] = 100.0 * new_error;
983 }
984 
985 // Helper generates a map from each current recoder_ code (ie softmax index)
986 // to the corresponding old_recoder code, or -1 if there isn't one.
987 std::vector<int> LSTMTrainer::MapRecoder(
988  const UNICHARSET& old_chset, const UnicharCompress& old_recoder) const {
989  int num_new_codes = recoder_.code_range();
990  int num_new_unichars = GetUnicharset().size();
991  std::vector<int> code_map(num_new_codes, -1);
992  for (int c = 0; c < num_new_codes; ++c) {
993  int old_code = -1;
994  // Find all new unichar_ids that recode to something that includes c.
995  // The <= is to include the null char, which may be beyond the unicharset.
996  for (int uid = 0; uid <= num_new_unichars; ++uid) {
997  RecodedCharID codes;
998  int length = recoder_.EncodeUnichar(uid, &codes);
999  int code_index = 0;
1000  while (code_index < length && codes(code_index) != c) ++code_index;
1001  if (code_index == length) continue;
1002  // The old unicharset must have the same unichar.
1003  int old_uid =
1004  uid < num_new_unichars
1005  ? old_chset.unichar_to_id(GetUnicharset().id_to_unichar(uid))
1006  : old_chset.size() - 1;
1007  if (old_uid == INVALID_UNICHAR_ID) continue;
1008  // The encoding of old_uid at the same code_index is the old code.
1009  RecodedCharID old_codes;
1010  if (code_index < old_recoder.EncodeUnichar(old_uid, &old_codes)) {
1011  old_code = old_codes(code_index);
1012  break;
1013  }
1014  }
1015  code_map[c] = old_code;
1016  }
1017  return code_map;
1018 }
1019 
1020 // Private version of InitCharSet above finishes the job after initializing
1021 // the mgr_ data member.
1023  EmptyConstructor();
1025  // Initialize the unicharset and recoder.
1026  if (!LoadCharsets(&mgr_)) {
1027  ASSERT_HOST(
1028  "Must provide a traineddata containing lstm_unicharset and"
1029  " lstm_recoder!\n" != nullptr);
1030  }
1031  SetNullChar();
1032 }
1033 
1034 // Helper computes and sets the null_char_.
1037  : GetUnicharset().size();
1038  RecodedCharID code;
1040  null_char_ = code(0);
1041 }
1042 
1043 // Factored sub-constructor sets up reasonable default values.
1045  align_win_ = NULL;
1046  target_win_ = NULL;
1047  ctc_win_ = NULL;
1048  recon_win_ = NULL;
1050  training_stage_ = 0;
1052  InitIterations();
1053 }
1054 
1055 // Outputs the string and periodically displays the given network inputs
1056 // as an image in the given window, and the corresponding labels at the
1057 // corresponding x_starts.
1058 // Returns false if the truth string is empty.
1060  const ImageData& trainingdata,
1061  const NetworkIO& fwd_outputs,
1062  const GenericVector<int>& truth_labels,
1063  const NetworkIO& outputs) {
1064  const STRING& truth_text = DecodeLabels(truth_labels);
1065  if (truth_text.string() == NULL || truth_text.length() <= 0) {
1066  tprintf("Empty truth string at decode time!\n");
1067  return false;
1068  }
1069  if (debug_interval_ != 0) {
1070  // Get class labels, xcoords and string.
1071  GenericVector<int> labels;
1072  GenericVector<int> xcoords;
1073  LabelsFromOutputs(outputs, &labels, &xcoords);
1074  STRING text = DecodeLabels(labels);
1075  tprintf("Iteration %d: ALIGNED TRUTH : %s\n",
1076  training_iteration(), text.string());
1077  if (debug_interval_ > 0 && training_iteration() % debug_interval_ == 0) {
1078  tprintf("TRAINING activation path for truth string %s\n",
1079  truth_text.string());
1080  DebugActivationPath(outputs, labels, xcoords);
1081  DisplayForward(inputs, labels, xcoords, "LSTMTraining", &align_win_);
1082  if (OutputLossType() == LT_CTC) {
1083  DisplayTargets(fwd_outputs, "CTC Outputs", &ctc_win_);
1084  DisplayTargets(outputs, "CTC Targets", &target_win_);
1085  }
1086  }
1087  }
1088  return true;
1089 }
1090 
1091 // Displays the network targets as line a line graph.
1093  const char* window_name, ScrollView** window) {
1094 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics.
1095  int width = targets.Width();
1096  int num_features = targets.NumFeatures();
1097  Network::ClearWindow(true, window_name, width * kTargetXScale, kTargetYScale,
1098  window);
1099  for (int c = 0; c < num_features; ++c) {
1100  int color = c % (ScrollView::GREEN_YELLOW - 1) + 2;
1101  (*window)->Pen(static_cast<ScrollView::Color>(color));
1102  int start_t = -1;
1103  for (int t = 0; t < width; ++t) {
1104  double target = targets.f(t)[c];
1105  target *= kTargetYScale;
1106  if (target >= 1) {
1107  if (start_t < 0) {
1108  (*window)->SetCursor(t - 1, 0);
1109  start_t = t;
1110  }
1111  (*window)->DrawTo(t, target);
1112  } else if (start_t >= 0) {
1113  (*window)->DrawTo(t, 0);
1114  (*window)->DrawTo(start_t - 1, 0);
1115  start_t = -1;
1116  }
1117  }
1118  if (start_t >= 0) {
1119  (*window)->DrawTo(width, 0);
1120  (*window)->DrawTo(start_t - 1, 0);
1121  }
1122  }
1123  (*window)->Update();
1124 #endif // GRAPHICS_DISABLED
1125 }
1126 
1127 // Builds a no-compromises target where the first positions should be the
1128 // truth labels and the rest is padded with the null_char_.
1130  const GenericVector<int>& truth_labels,
1131  NetworkIO* targets) {
1132  if (truth_labels.size() > targets->Width()) {
1133  tprintf("Error: transcription %s too long to fit into target of width %d\n",
1134  DecodeLabels(truth_labels).string(), targets->Width());
1135  return false;
1136  }
1137  for (int i = 0; i < truth_labels.size() && i < targets->Width(); ++i) {
1138  targets->SetActivations(i, truth_labels[i], 1.0);
1139  }
1140  for (int i = truth_labels.size(); i < targets->Width(); ++i) {
1141  targets->SetActivations(i, null_char_, 1.0);
1142  }
1143  return true;
1144 }
1145 
1146 // Builds a target using standard CTC. truth_labels should be pre-padded with
1147 // nulls wherever desired. They don't have to be between all labels.
1148 // outputs is input-output, as it gets clipped to minimum probability.
1150  NetworkIO* outputs, NetworkIO* targets) {
1151  // Bottom-clip outputs to a minimum probability.
1152  CTC::NormalizeProbs(outputs);
1153  return CTC::ComputeCTCTargets(truth_labels, null_char_,
1154  outputs->float_array(), targets);
1155 }
1156 
1157 // Computes network errors, and stores the results in the rolling buffers,
1158 // along with the supplied text_error.
1159 // Returns the delta error of the current sample (not running average.)
1161  double char_error, double word_error) {
1163  // Delta error is the fraction of timesteps with >0.5 error in the top choice
1164  // score. If zero, then the top choice characters are guaranteed correct,
1165  // even when there is residue in the RMS error.
1166  double delta_error = ComputeWinnerError(deltas);
1167  UpdateErrorBuffer(delta_error, ET_DELTA);
1168  UpdateErrorBuffer(word_error, ET_WORD_RECERR);
1169  UpdateErrorBuffer(char_error, ET_CHAR_ERROR);
1170  // Skip ratio measures the difference between sample_iteration_ and
1171  // training_iteration_, which reflects the number of unusable samples,
1172  // usually due to unencodable truth text, or the text not fitting in the
1173  // space for the output.
1174  double skip_count = sample_iteration_ - prev_sample_iteration_;
1175  UpdateErrorBuffer(skip_count, ET_SKIP_RATIO);
1176  return delta_error;
1177 }
1178 
1179 // Computes the network activation RMS error rate.
1181  double total_error = 0.0;
1182  int width = deltas.Width();
1183  int num_classes = deltas.NumFeatures();
1184  for (int t = 0; t < width; ++t) {
1185  const float* class_errs = deltas.f(t);
1186  for (int c = 0; c < num_classes; ++c) {
1187  double error = class_errs[c];
1188  total_error += error * error;
1189  }
1190  }
1191  return sqrt(total_error / (width * num_classes));
1192 }
1193 
1194 // Computes network activation winner error rate. (Number of values that are
1195 // in error by >= 0.5 divided by number of time-steps.) More closely related
1196 // to final character error than RMS, but still directly calculable from
1197 // just the deltas. Because of the binary nature of the targets, zero winner
1198 // error is a sufficient but not necessary condition for zero char error.
1200  int num_errors = 0;
1201  int width = deltas.Width();
1202  int num_classes = deltas.NumFeatures();
1203  for (int t = 0; t < width; ++t) {
1204  const float* class_errs = deltas.f(t);
1205  for (int c = 0; c < num_classes; ++c) {
1206  float abs_delta = fabs(class_errs[c]);
1207  // TODO(rays) Filtering cases where the delta is very large to cut out
1208  // GT errors doesn't work. Find a better way or get better truth.
1209  if (0.5 <= abs_delta)
1210  ++num_errors;
1211  }
1212  }
1213  return static_cast<double>(num_errors) / width;
1214 }
1215 
1216 // Computes a very simple bag of chars char error rate.
1218  const GenericVector<int>& ocr_str) {
1219  GenericVector<int> label_counts;
1220  label_counts.init_to_size(NumOutputs(), 0);
1221  int truth_size = 0;
1222  for (int i = 0; i < truth_str.size(); ++i) {
1223  if (truth_str[i] != null_char_) {
1224  ++label_counts[truth_str[i]];
1225  ++truth_size;
1226  }
1227  }
1228  for (int i = 0; i < ocr_str.size(); ++i) {
1229  if (ocr_str[i] != null_char_) {
1230  --label_counts[ocr_str[i]];
1231  }
1232  }
1233  int char_errors = 0;
1234  for (int i = 0; i < label_counts.size(); ++i) {
1235  char_errors += abs(label_counts[i]);
1236  }
1237  if (truth_size == 0) {
1238  return (char_errors == 0) ? 0.0 : 1.0;
1239  }
1240  return static_cast<double>(char_errors) / truth_size;
1241 }
1242 
1243 // Computes word recall error rate using a very simple bag of words algorithm.
1244 // NOTE that this is destructive on both input strings.
1245 double LSTMTrainer::ComputeWordError(STRING* truth_str, STRING* ocr_str) {
1246  typedef std::unordered_map<std::string, int, std::hash<std::string> > StrMap;
1247  GenericVector<STRING> truth_words, ocr_words;
1248  truth_str->split(' ', &truth_words);
1249  if (truth_words.empty()) return 0.0;
1250  ocr_str->split(' ', &ocr_words);
1251  StrMap word_counts;
1252  for (int i = 0; i < truth_words.size(); ++i) {
1253  std::string truth_word(truth_words[i].string());
1254  StrMap::iterator it = word_counts.find(truth_word);
1255  if (it == word_counts.end())
1256  word_counts.insert(std::make_pair(truth_word, 1));
1257  else
1258  ++it->second;
1259  }
1260  for (int i = 0; i < ocr_words.size(); ++i) {
1261  std::string ocr_word(ocr_words[i].string());
1262  StrMap::iterator it = word_counts.find(ocr_word);
1263  if (it == word_counts.end())
1264  word_counts.insert(std::make_pair(ocr_word, -1));
1265  else
1266  --it->second;
1267  }
1268  int word_recall_errs = 0;
1269  for (StrMap::const_iterator it = word_counts.begin(); it != word_counts.end();
1270  ++it) {
1271  if (it->second > 0) word_recall_errs += it->second;
1272  }
1273  return static_cast<double>(word_recall_errs) / truth_words.size();
1274 }
1275 
1276 // Updates the error buffer and corresponding mean of the given type with
1277 // the new_error.
1278 void LSTMTrainer::UpdateErrorBuffer(double new_error, ErrorTypes type) {
1280  error_buffers_[type][index] = new_error;
1281  // Compute the mean error.
1282  int mean_count = MIN(training_iteration_ + 1, error_buffers_[type].size());
1283  double buffer_sum = 0.0;
1284  for (int i = 0; i < mean_count; ++i) buffer_sum += error_buffers_[type][i];
1285  double mean = buffer_sum / mean_count;
1286  // Trim precision to 1/1000 of 1%.
1287  error_rates_[type] = IntCastRounded(100000.0 * mean) / 1000.0;
1288 }
1289 
1290 // Rolls error buffers and reports the current means.
1293  if (NewSingleError(ET_DELTA) > 0.0)
1295  else
1298  if (debug_interval_ != 0) {
1299  tprintf("Mean rms=%g%%, delta=%g%%, train=%g%%(%g%%), skip ratio=%g%%\n",
1303  }
1304 }
1305 
1306 // Given that error_rate is either a new min or max, updates the best/worst
1307 // error rates, and record of progress.
1308 // Tester is an externally supplied callback function that tests on some
1309 // data set with a given model and records the error rates in a graph.
1310 STRING LSTMTrainer::UpdateErrorGraph(int iteration, double error_rate,
1311  const GenericVector<char>& model_data,
1312  TestCallback tester) {
1313  if (error_rate > best_error_rate_
1314  && iteration < best_iteration_ + kErrorGraphInterval) {
1315  // Too soon to record a new point.
1316  if (tester != NULL && !worst_model_data_.empty()) {
1319  return tester->Run(worst_iteration_, NULL, mgr_, CurrentTrainingStage());
1320  } else {
1321  return "";
1322  }
1323  }
1324  STRING result;
1325  // NOTE: there are 2 asymmetries here:
1326  // 1. We are computing the global minimum, but the local maximum in between.
1327  // 2. If the tester returns an empty string, indicating that it is busy,
1328  // call it repeatedly on new local maxima to test the previous min, but
1329  // not the other way around, as there is little point testing the maxima
1330  // between very frequent minima.
1331  if (error_rate < best_error_rate_) {
1332  // This is a new (global) minimum.
1333  if (tester != nullptr && !worst_model_data_.empty()) {
1336  result = tester->Run(worst_iteration_, worst_error_rates_, mgr_,
1339  best_model_data_ = model_data;
1340  }
1341  best_error_rate_ = error_rate;
1342  memcpy(best_error_rates_, error_rates_, sizeof(error_rates_));
1343  best_iteration_ = iteration;
1344  best_error_history_.push_back(error_rate);
1345  best_error_iterations_.push_back(iteration);
1346  // Compute 2% decay time.
1347  double two_percent_more = error_rate + 2.0;
1348  int i;
1349  for (i = best_error_history_.size() - 1;
1350  i >= 0 && best_error_history_[i] < two_percent_more; --i) {
1351  }
1352  int old_iteration = i >= 0 ? best_error_iterations_[i] : 0;
1353  improvement_steps_ = iteration - old_iteration;
1354  tprintf("2 Percent improvement time=%d, best error was %g @ %d\n",
1355  improvement_steps_, i >= 0 ? best_error_history_[i] : 100.0,
1356  old_iteration);
1357  } else if (error_rate > best_error_rate_) {
1358  // This is a new (local) maximum.
1359  if (tester != NULL) {
1360  if (!best_model_data_.empty()) {
1363  result = tester->Run(best_iteration_, best_error_rates_, mgr_,
1365  } else if (!worst_model_data_.empty()) {
1366  // Allow for multiple data points with "worst" error rate.
1369  result = tester->Run(worst_iteration_, worst_error_rates_, mgr_,
1371  }
1372  if (result.length() > 0)
1374  worst_model_data_ = model_data;
1375  }
1376  }
1377  worst_error_rate_ = error_rate;
1378  memcpy(worst_error_rates_, error_rates_, sizeof(error_rates_));
1379  worst_iteration_ = iteration;
1380  return result;
1381 }
1382 
1383 } // namespace tesseract.
virtual STRING spec() const
Definition: network.h:141
int CurrentTrainingStage() const
Definition: lstmtrainer.h:211
bool empty() const
Definition: genericvector.h:91
#define MIN(x, y)
Definition: ndminx.h:28
void DisplayForward(const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
int FWrite(const void *buffer, int size, int count)
Definition: serialis.cpp:148
virtual void Update(float learning_rate, float momentum, float adam_beta, int num_samples)
Definition: network.h:231
static const int kRollingBufferSize_
Definition: lstmtrainer.h:478
bool SaveFile(const STRING &filename, FileWriter writer) const
void SetIteration(int iteration)
void Resize(const NetworkIO &src, int num_features)
Definition: networkio.h:45
const double kLearningRateDecay
Definition: lstmtrainer.cpp:52
double ComputeWordError(STRING *truth_str, STRING *ocr_str)
bool TryLoadingCheckpoint(const char *filename, const char *old_traineddata)
void DebugActivationPath(const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
GenericVector< char > best_trainer_
Definition: lstmtrainer.h:447
bool encode_string(const char *str, bool give_up_on_failure, GenericVector< UNICHAR_ID > *encoding, GenericVector< char > *lengths, int *encoded_length) const
Definition: unicharset.cpp:256
const int kTargetXScale
Definition: lstmtrainer.cpp:70
int NumOutputs() const
Definition: network.h:123
void DisplayTargets(const NetworkIO &targets, const char *window_name, ScrollView **window)
GenericVector< double > best_error_history_
Definition: lstmtrainer.h:457
int NumFeatures() const
Definition: networkio.h:111
int InitTensorFlowNetwork(const std::string &tf_proto)
void FillErrorBuffer(double new_error, ErrorTypes type)
double learning_rate() const
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
double worst_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:438
void OpenWrite(GenericVector< char > *data)
Definition: serialis.cpp:125
double ComputeRMSError(const NetworkIO &deltas)
virtual R Run(A1, A2)=0
const STRING & imagefilename() const
Definition: imagedata.h:124
double ComputeErrorRates(const NetworkIO &deltas, double char_error, double word_error)
double ComputeCharError(const GenericVector< int > &truth_str, const GenericVector< int > &ocr_str)
double ComputeWinnerError(const NetworkIO &deltas)
void Decode(const NetworkIO &output, double dict_ratio, double cert_offset, double worst_dict_cert, const UNICHARSET *charset)
Definition: recodebeam.cpp:76
bool LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)
Definition: imagedata.cpp:573
double best_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:432
void add_str_int(const char *str, int number)
Definition: strngs.cpp:381
void SaveRecognitionDump(GenericVector< char > *data) const
void SubtractAllFromFloat(const NetworkIO &src)
Definition: networkio.cpp:829
GenericVector< char > worst_model_data_
Definition: lstmtrainer.h:445
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
Definition: tesscallback.h:116
const int kTargetYScale
Definition: lstmtrainer.cpp:71
const GENERIC_2D_ARRAY< float > & float_array() const
Definition: networkio.h:139
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
bool ComputeCTCTargets(const GenericVector< int > &truth_labels, NetworkIO *outputs, NetworkIO *targets)
const int kMinStartedErrorRate
Definition: lstmtrainer.cpp:60
bool InitNetwork(const STRING &network_spec, int append_index, int net_flags, float weight_range, float learning_rate, float momentum, float adam_beta)
void LogIterations(const char *intro_str, STRING *log_msg) const
float error_rate_of_last_saved_best_
Definition: lstmtrainer.h:452
CheckPointReader checkpoint_reader_
Definition: lstmtrainer.h:424
bool TestFlag(NetworkFlags flag) const
Definition: network.h:144
SVEvent * AwaitEvent(SVEventType type)
Definition: scrollview.cpp:449
Network * GetLayer(const STRING &id) const
void StartSubtrainer(STRING *log_msg)
int size() const
Definition: genericvector.h:72
bool Serialize(const TessdataManager *mgr, TFile *fp) const
bool ComputeTextTargets(const NetworkIO &outputs, const GenericVector< int > &truth_labels, NetworkIO *targets)
void ScaleLayerLearningRate(const STRING &id, double factor)
double CharError() const
Definition: lstmtrainer.h:139
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
Definition: network.cpp:309
static string CleanupString(const char *utf8_str)
Definition: unicharset.h:241
ScrollView * target_win_
Definition: lstmtrainer.h:399
TessdataManager mgr_
Definition: lstmtrainer.h:483
const int kMinStallIterations
Definition: lstmtrainer.cpp:47
CachingStrategy
Definition: imagedata.h:40
static void NormalizeProbs(NetworkIO *probs)
Definition: ctc.h:36
virtual void SetEnableTraining(TrainingState state)
Definition: network.cpp:112
bool EncodeString(const STRING &str, GenericVector< int > *labels) const
Definition: lstmtrainer.h:246
static bool InitNetwork(int num_outputs, STRING network_spec, int append_index, int net_flags, float weight_range, TRand *randomizer, Network **network)
ScrollView * ctc_win_
Definition: lstmtrainer.h:401
#define tprintf(...)
Definition: tprintf.h:31
bool GetComponent(TessdataType type, TFile *fp)
virtual void CountAlternators(const Network &other, double *same, double *changed) const
Definition: network.h:236
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const
bool SaveTraineddata(const STRING &filename)
int learning_iteration() const
Definition: lstmtrainer.h:149
virtual bool Serialize(SerializeAmount serialize_amount, const TessdataManager *mgr, TFile *fp) const
STRING UpdateErrorGraph(int iteration, double error_rate, const GenericVector< char > &model_data, TestCallback tester)
virtual StaticShape InputShape() const
Definition: network.h:127
uint8_t uinT8
Definition: host.h:35
const int kNumPagesPerBatch
Definition: lstmtrainer.cpp:58
void truncate(int size)
static bool ComputeCTCTargets(const GenericVector< int > &truth_labels, int null_char, const GENERIC_2D_ARRAY< float > &outputs, NetworkIO *targets)
Definition: ctc.cpp:53
bool IsTraining() const
Definition: network.h:115
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
bool(* FileWriter)(const GenericVector< char > &data, const STRING &filename)
void ExtractBestPathAsLabels(GenericVector< int > *labels, GenericVector< int > *xcoords) const
Definition: recodebeam.cpp:100
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
bool MaintainCheckpoints(TestCallback tester, STRING *log_msg)
void add_str_double(const char *str, double number)
Definition: strngs.cpp:391
LossType OutputLossType() const
const double kBestCheckpointFraction
Definition: lstmtrainer.cpp:68
int size() const
Definition: unicharset.h:338
const char * string() const
Definition: strngs.cpp:198
int push_back(T object)
bool has_special_codes() const
Definition: unicharset.h:721
double SignedRand(double range)
Definition: helpers.h:60
Trainability GridSearchDictParams(const ImageData *trainingdata, int iteration, double min_dict_ratio, double dict_ratio_step, double max_dict_ratio, double min_cert_offset, double cert_offset_step, double max_cert_offset, STRING *results)
LIST search(LIST list, void *key, int_compare is_equal)
Definition: oldlist.cpp:371
const int kNumAdjustmentIterations
Definition: lstmtrainer.cpp:54
float * f(int t)
Definition: networkio.h:115
void RecognizeLine(const ImageData &image_data, bool invert, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words)
bool TransitionTrainingStage(float error_threshold)
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)
Definition: network.h:273
STRING DecodeLabels(const GenericVector< int > &labels)
ScrollView * recon_win_
Definition: lstmtrainer.h:403
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
Definition: lstmtrainer.h:259
bool Serialize(FILE *fp) const
double NewSingleError(ErrorTypes type) const
Definition: lstmtrainer.h:154
CheckPointWriter checkpoint_writer_
Definition: lstmtrainer.h:425
const int kErrorGraphInterval
Definition: lstmtrainer.cpp:56
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:207
Definition: strngs.h:45
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
virtual R Run(A1, A2, A3, A4)=0
bool Open(const STRING &filename, FileReader reader)
Definition: serialis.cpp:38
bool ReadLocalTrainingDump(const TessdataManager *mgr, const char *data, int size)
const STRING & name() const
Definition: network.h:138
int num_weights() const
Definition: network.h:119
#define ASSERT_HOST(x)
Definition: errcode.h:84
float GetLayerLearningRate(const STRING &id) const
int page_number() const
Definition: imagedata.h:130
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
virtual StaticShape OutputShape(const StaticShape &input_shape) const
Definition: network.h:133
std::vector< int > MapRecoder(const UNICHARSET &old_chset, const UnicharCompress &old_recoder) const
bool AnySuspiciousTruth(float confidence_thr) const
Definition: networkio.cpp:584
bool LoadAllTrainingData(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, bool randomly_rotate)
bool DeSerialize(bool swap, FILE *fp)
int Width() const
Definition: networkio.h:107
bool load_from_file(const char *const filename, bool skip_fragments)
Definition: unicharset.h:387
STRING DumpFilename() const
const double kImprovementFraction
Definition: lstmtrainer.cpp:66
GenericVector< int > best_error_iterations_
Definition: lstmtrainer.h:458
const double kSubTrainerMarginFraction
Definition: lstmtrainer.cpp:50
const double kMinDivergenceRate
Definition: lstmtrainer.cpp:45
int FReadEndian(void *buffer, int size, int count)
Definition: serialis.cpp:97
virtual void DebugWeights()
Definition: network.h:218
GenericVector< STRING > EnumerateLayers() const
virtual R Run(A1, A2, A3)=0
static const float kMinCertainty
Definition: recodebeam.h:213
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
bool LoadCharsets(const TessdataManager *mgr)
void OverwriteEntry(TessdataType type, const char *data, int size)
const double kHighConfidence
Definition: lstmtrainer.cpp:64
void PrepareLogMsg(STRING *log_msg) const
void SetActivations(int t, int label, float ok_score)
Definition: networkio.cpp:542
const GenericVector< TBOX > & boxes() const
Definition: imagedata.h:148
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
const UNICHARSET & GetUnicharset() const
int ReduceLayerLearningRates(double factor, int num_samples, LSTMTrainer *samples_trainer)
bool Init(const char *data_file_name)
const STRING & transcription() const
Definition: imagedata.h:145
DocumentCache training_data_
Definition: lstmtrainer.h:414
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
virtual bool DeSerialize(const TessdataManager *mgr, TFile *fp)
void UpdateErrorBuffer(double new_error, ErrorTypes type)
const STRING & language() const
Definition: imagedata.h:139
void ReduceLearningRates(LSTMTrainer *samples_trainer, STRING *log_msg)
int IntCastRounded(double x)
Definition: helpers.h:179
ScrollView * align_win_
Definition: lstmtrainer.h:397
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
Definition: lstmtrainer.h:291
void init_to_size(int size, T t)
const double kStageTransitionThreshold
Definition: lstmtrainer.cpp:62
virtual int RemapOutputs(int old_no, const std::vector< int > &code_map)
Definition: network.h:186
void split(const char c, GenericVector< STRING > *splited)
Definition: strngs.cpp:286
int FRead(void *buffer, int size, int count)
Definition: serialis.cpp:108
int64_t inT64
Definition: host.h:40
SubTrainerResult UpdateSubtrainer(STRING *log_msg)
NetworkScratch scratch_space_
inT32 length() const
Definition: strngs.cpp:193
bool DebugLSTMTraining(const NetworkIO &inputs, const ImageData &trainingdata, const NetworkIO &fwd_outputs, const GenericVector< int > &truth_labels, const NetworkIO &outputs)
void SetVersionString(const string &v_str)
GenericVector< char > best_model_data_
Definition: lstmtrainer.h:444
void ScaleLearningRate(double factor)