tesseract  4.00.00dev
lstmtester.cpp
Go to the documentation of this file.
1 // File: lstmtester.cpp
3 // Description: Top-level line evaluation class for LSTM-based networks.
4 // Author: Ray Smith
5 // Created: Wed Nov 23 11:18:06 PST 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 
19 #include "lstmtester.h"
20 #include "genericvector.h"
21 
22 namespace tesseract {
23 
25  : test_data_(max_memory), total_pages_(0), async_running_(false) {}
26 
27 // Loads a set of lstmf files that were created using the lstm.train config to
28 // tesseract into memory ready for testing. Returns false if nothing was
29 // loaded. The arg is a filename of a file that lists the filenames.
30 bool LSTMTester::LoadAllEvalData(const STRING& filenames_file) {
31  GenericVector<STRING> filenames;
32  if (!LoadFileLinesToStrings(filenames_file, &filenames)) {
33  tprintf("Failed to load list of eval filenames from %s\n",
34  filenames_file.string());
35  return false;
36  }
37  return LoadAllEvalData(filenames);
38 }
39 
40 // Loads a set of lstmf files that were created using the lstm.train config to
41 // tesseract into memory ready for testing. Returns false if nothing was
42 // loaded.
44  test_data_.Clear();
45  bool result = test_data_.LoadDocuments(filenames, CS_SEQUENTIAL, nullptr);
46  total_pages_ = test_data_.TotalPages();
47  return result;
48 }
49 
50 // Runs an evaluation asynchronously on the stored data and returns a string
51 // describing the results of the previous test.
52 STRING LSTMTester::RunEvalAsync(int iteration, const double* training_errors,
53  const GenericVector<char>& model_data,
54  int training_stage) {
55  STRING result;
56  if (total_pages_ == 0) {
57  result.add_str_int("No test data at iteration", iteration);
58  return result;
59  }
60  if (!LockIfNotRunning()) {
61  result.add_str_int("Previous test incomplete, skipping test at iteration",
62  iteration);
63  return result;
64  }
65  // Save the args.
66  STRING prev_result = test_result_;
67  test_result_ = "";
68  if (training_errors != nullptr) {
69  test_iteration_ = iteration;
70  test_training_errors_ = training_errors;
71  test_model_data_ = model_data;
72  test_training_stage_ = training_stage;
73  SVSync::StartThread(&LSTMTester::ThreadFunc, this);
74  } else {
75  UnlockRunning();
76  }
77  return prev_result;
78 }
79 
80 // Runs an evaluation synchronously on the stored data and returns a string
81 // describing the results.
82 STRING LSTMTester::RunEvalSync(int iteration, const double* training_errors,
83  const GenericVector<char>& model_data,
84  int training_stage) {
85  LSTMTrainer trainer;
86  if (!trainer.ReadTrainingDump(model_data, &trainer)) {
87  return "Deserialize failed";
88  }
89  int eval_iteration = 0;
90  double char_error = 0.0;
91  double word_error = 0.0;
92  int error_count = 0;
93  while (error_count < total_pages_) {
94  const ImageData* trainingdata = test_data_.GetPageBySerial(eval_iteration);
95  trainer.SetIteration(++eval_iteration);
96  NetworkIO fwd_outputs, targets;
97  if (trainer.PrepareForBackward(trainingdata, &fwd_outputs, &targets) !=
98  UNENCODABLE) {
99  char_error += trainer.NewSingleError(tesseract::ET_CHAR_ERROR);
100  word_error += trainer.NewSingleError(tesseract::ET_WORD_RECERR);
101  ++error_count;
102  }
103  }
104  char_error *= 100.0 / total_pages_;
105  word_error *= 100.0 / total_pages_;
106  STRING result;
107  result.add_str_int("At iteration ", iteration);
108  result.add_str_int(", stage ", training_stage);
109  result.add_str_double(", Eval Char error rate=", char_error);
110  result.add_str_double(", Word error rate=", word_error);
111  return result;
112 }
113 
114 // Static helper thread function for RunEvalAsync, with a specific signature
115 // required by SVSync::StartThread. Actually a member function pretending to
116 // be static, its arg is a this pointer that it will cast back to LSTMTester*
117 // to call RunEvalSync using the stored args that RunEvalAsync saves in *this.
118 // LockIfNotRunning must have returned true before calling ThreadFunc, and
119 // it will call UnlockRunning to release the lock after RunEvalSync completes.
120 /* static */
121 void* LSTMTester::ThreadFunc(void* lstmtester_void) {
122  LSTMTester* lstmtester = static_cast<LSTMTester*>(lstmtester_void);
123  lstmtester->test_result_ = lstmtester->RunEvalSync(
124  lstmtester->test_iteration_, lstmtester->test_training_errors_,
125  lstmtester->test_model_data_, lstmtester->test_training_stage_);
126  lstmtester->UnlockRunning();
127  return lstmtester_void;
128 }
129 
130 // Returns true if there is currently nothing running, and takes the lock
131 // if there is nothing running.
132 bool LSTMTester::LockIfNotRunning() {
133  SVAutoLock lock(&running_mutex_);
134  if (async_running_) return false;
135  async_running_ = true;
136  return true;
137 }
138 
139 // Releases the running lock.
140 void LSTMTester::UnlockRunning() {
141  SVAutoLock lock(&running_mutex_);
142  async_running_ = false;
143 }
144 
145 } // namespace tesseract
const ImageData * GetPageBySerial(int serial)
Definition: imagedata.h:335
void add_str_int(const char *str, int number)
Definition: strngs.cpp:381
int64_t inT64
Definition: host.h:40
#define tprintf(...)
Definition: tprintf.h:31
const char * string() const
Definition: strngs.cpp:198
LSTMTester(inT64 max_memory)
Definition: lstmtester.cpp:24
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer)
Definition: strngs.h:45
static void StartThread(void *(*func)(void *), void *arg)
Create new thread.
Definition: svutil.cpp:87
double NewSingleError(ErrorTypes type) const
Definition: lstmtrainer.h:154
void add_str_double(const char *str, double number)
Definition: strngs.cpp:391
bool LoadFileLinesToStrings(const STRING &filename, GenericVector< STRING > *lines)
bool LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)
Definition: imagedata.cpp:572
STRING RunEvalSync(int iteration, const double *training_errors, const GenericVector< char > &model_data, int training_stage)
Definition: lstmtester.cpp:82
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
bool LoadAllEvalData(const STRING &filenames_file)
Definition: lstmtester.cpp:30
void SetIteration(int iteration)
STRING RunEvalAsync(int iteration, const double *training_errors, const GenericVector< char > &model_data, int training_stage)
Definition: lstmtester.cpp:52