tesseract  4.00.00dev
lstmtraining.cpp
Go to the documentation of this file.
1 // File: lstmtraining.cpp
3 // Description: Training program for LSTM-based networks.
4 // Author: Ray Smith
5 // Created: Fri May 03 11:05: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 #ifndef USE_STD_NAMESPACE
20 #include "base/commandlineflags.h"
21 #endif
22 #include "commontraining.h"
23 #include "lstmtester.h"
24 #include "lstmtrainer.h"
25 #include "params.h"
26 #include "strngs.h"
27 #include "tprintf.h"
29 
30 INT_PARAM_FLAG(debug_interval, 0, "How often to display the alignment.");
31 STRING_PARAM_FLAG(net_spec, "", "Network specification");
32 INT_PARAM_FLAG(train_mode, 80, "Controls gross training behavior.");
33 INT_PARAM_FLAG(net_mode, 192, "Controls network behavior.");
34 INT_PARAM_FLAG(perfect_sample_delay, 4,
35  "How many imperfect samples between perfect ones.");
36 DOUBLE_PARAM_FLAG(target_error_rate, 0.01, "Final error rate in percent.");
37 DOUBLE_PARAM_FLAG(weight_range, 0.1, "Range of initial random weights.");
38 DOUBLE_PARAM_FLAG(learning_rate, 1.0e-4, "Weight factor for new deltas.");
39 DOUBLE_PARAM_FLAG(momentum, 0.9, "Decay factor for repeating deltas.");
40 INT_PARAM_FLAG(max_image_MB, 6000, "Max memory to use for images.");
41 STRING_PARAM_FLAG(continue_from, "", "Existing model to extend");
42 STRING_PARAM_FLAG(model_output, "lstmtrain", "Basename for output models");
43 STRING_PARAM_FLAG(script_dir, "",
44  "Required to set unicharset properties or"
45  " use unicharset compression.");
46 STRING_PARAM_FLAG(train_listfile, "",
47  "File listing training files in lstmf training format.");
48 STRING_PARAM_FLAG(eval_listfile, "",
49  "File listing eval files in lstmf training format.");
50 BOOL_PARAM_FLAG(stop_training, false,
51  "Just convert the training model to a runtime model.");
52 INT_PARAM_FLAG(append_index, -1, "Index in continue_from Network at which to"
53  " attach the new network defined by net_spec");
54 BOOL_PARAM_FLAG(debug_network, false,
55  "Get info on distribution of weight values");
56 INT_PARAM_FLAG(max_iterations, 0, "If set, exit after this many iterations");
58 
59 // Number of training images to train between calls to MaintainCheckpoints.
60 const int kNumPagesPerBatch = 100;
61 
62 // Apart from command-line flags, input is a collection of lstmf files, that
63 // were previously created using tesseract with the lstm.train config file.
64 // The program iterates over the inputs, feeding the data to the network,
65 // until the error rate reaches a specified target or max_iterations is reached.
66 int main(int argc, char **argv) {
67  ParseArguments(&argc, &argv);
68  // Purify the model name in case it is based on the network string.
69  if (FLAGS_model_output.empty()) {
70  tprintf("Must provide a --model_output!\n");
71  return 1;
72  }
73  STRING model_output = FLAGS_model_output.c_str();
74  for (int i = 0; i < model_output.length(); ++i) {
75  if (model_output[i] == '[' || model_output[i] == ']')
76  model_output[i] = '-';
77  if (model_output[i] == '(' || model_output[i] == ')')
78  model_output[i] = '_';
79  }
80  // Setup the trainer.
81  STRING checkpoint_file = FLAGS_model_output.c_str();
82  checkpoint_file += "_checkpoint";
83  STRING checkpoint_bak = checkpoint_file + ".bak";
84  tesseract::LSTMTrainer trainer(
85  nullptr, nullptr, nullptr, nullptr, FLAGS_model_output.c_str(),
86  checkpoint_file.c_str(), FLAGS_debug_interval,
87  static_cast<inT64>(FLAGS_max_image_MB) * 1048576);
88 
89  // Reading something from an existing model doesn't require many flags,
90  // so do it now and exit.
91  if (FLAGS_stop_training || FLAGS_debug_network) {
92  if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str())) {
93  tprintf("Failed to read continue from: %s\n",
94  FLAGS_continue_from.c_str());
95  return 1;
96  }
97  if (FLAGS_debug_network) {
98  trainer.DebugNetwork();
99  } else {
100  if (FLAGS_train_mode & tesseract::TF_INT_MODE)
101  trainer.ConvertToInt();
102  GenericVector<char> recognizer_data;
103  trainer.SaveRecognitionDump(&recognizer_data);
104  if (!tesseract::SaveDataToFile(recognizer_data,
105  FLAGS_model_output.c_str())) {
106  tprintf("Failed to write recognition model : %s\n",
107  FLAGS_model_output.c_str());
108  }
109  }
110  return 0;
111  }
112 
113  // Get the list of files to process.
114  if (FLAGS_train_listfile.empty()) {
115  tprintf("Must supply a list of training filenames! --train_listfile\n");
116  return 1;
117  }
118  GenericVector<STRING> filenames;
119  if (!tesseract::LoadFileLinesToStrings(FLAGS_train_listfile.c_str(),
120  &filenames)) {
121  tprintf("Failed to load list of training filenames from %s\n",
122  FLAGS_train_listfile.c_str());
123  return 1;
124  }
125 
126  UNICHARSET unicharset;
127  // Checkpoints always take priority if they are available.
128  if (trainer.TryLoadingCheckpoint(checkpoint_file.string()) ||
129  trainer.TryLoadingCheckpoint(checkpoint_bak.string())) {
130  tprintf("Successfully restored trainer from %s\n",
131  checkpoint_file.string());
132  } else {
133  if (!FLAGS_continue_from.empty()) {
134  // Load a past model file to improve upon.
135  if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str())) {
136  tprintf("Failed to continue from: %s\n", FLAGS_continue_from.c_str());
137  return 1;
138  }
139  tprintf("Continuing from %s\n", FLAGS_continue_from.c_str());
140  trainer.InitIterations();
141  }
142  if (FLAGS_continue_from.empty() || FLAGS_append_index >= 0) {
143  // We need a unicharset to start from scratch or append.
144  string unicharset_str;
145  // Character coding to be used by the classifier.
146  if (!unicharset.load_from_file(FLAGS_U.c_str())) {
147  tprintf("Error: must provide a -U unicharset!\n");
148  return 1;
149  }
150  tesseract::SetupBasicProperties(true, &unicharset);
151  if (FLAGS_append_index >= 0) {
152  tprintf("Appending a new network to an old one!!");
153  if (FLAGS_continue_from.empty()) {
154  tprintf("Must set --continue_from for appending!\n");
155  return 1;
156  }
157  }
158  // We are initializing from scratch.
159  trainer.InitCharSet(unicharset, FLAGS_script_dir.c_str(),
160  FLAGS_train_mode);
161  if (!trainer.InitNetwork(FLAGS_net_spec.c_str(), FLAGS_append_index,
162  FLAGS_net_mode, FLAGS_weight_range,
163  FLAGS_learning_rate, FLAGS_momentum)) {
164  tprintf("Failed to create network from spec: %s\n",
165  FLAGS_net_spec.c_str());
166  return 1;
167  }
168  trainer.set_perfect_delay(FLAGS_perfect_sample_delay);
169  }
170  }
171  if (!trainer.LoadAllTrainingData(filenames)) {
172  tprintf("Load of images failed!!\n");
173  return 1;
174  }
175 
176  tesseract::LSTMTester tester(static_cast<inT64>(FLAGS_max_image_MB) *
177  1048576);
178  tesseract::TestCallback tester_callback = nullptr;
179  if (!FLAGS_eval_listfile.empty()) {
180  if (!tester.LoadAllEvalData(FLAGS_eval_listfile.c_str())) {
181  tprintf("Failed to load eval data from: %s\n",
182  FLAGS_eval_listfile.c_str());
183  return 1;
184  }
185  tester_callback =
187  }
188  do {
189  // Train a few.
190  int iteration = trainer.training_iteration();
191  for (int target_iteration = iteration + kNumPagesPerBatch;
192  iteration < target_iteration;
193  iteration = trainer.training_iteration()) {
194  trainer.TrainOnLine(&trainer, false);
195  }
196  STRING log_str;
197  trainer.MaintainCheckpoints(tester_callback, &log_str);
198  tprintf("%s\n", log_str.string());
199  } while (trainer.best_error_rate() > FLAGS_target_error_rate &&
200  (trainer.training_iteration() < FLAGS_max_iterations ||
201  FLAGS_max_iterations == 0));
202  delete tester_callback;
203  tprintf("Finished! Error rate = %g\n", trainer.best_error_rate());
204  return 0;
205 } /* main */
206 
207 
double best_error_rate() const
Definition: lstmtrainer.h:143
const int kNumPagesPerBatch
void SetupBasicProperties(bool report_errors, bool decompose, UNICHARSET *unicharset)
int64_t inT64
Definition: host.h:40
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
Definition: tesscallback.h:116
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
void InitCharSet(const UNICHARSET &unicharset, const STRING &script_dir, int train_flags)
DECLARE_STRING_PARAM_FLAG(U)
bool InitNetwork(const STRING &network_spec, int append_index, int net_flags, float weight_range, float learning_rate, float momentum)
#define tprintf(...)
Definition: tprintf.h:31
const char * string() const
Definition: strngs.cpp:198
bool TryLoadingCheckpoint(const char *filename)
inT32 length() const
Definition: strngs.cpp:193
void ParseArguments(int *argc, char ***argv)
DOUBLE_PARAM_FLAG(target_error_rate, 0.01, "Final error rate in percent.")
bool MaintainCheckpoints(TestCallback tester, STRING *log_msg)
void set_perfect_delay(int delay)
Definition: lstmtrainer.h:151
BOOL_PARAM_FLAG(stop_training, false, "Just convert the training model to a runtime model.")
Definition: strngs.h:45
INT_PARAM_FLAG(debug_interval, 0, "How often to display the alignment.")
STRING_PARAM_FLAG(net_spec, "", "Network specification")
bool LoadFileLinesToStrings(const STRING &filename, GenericVector< STRING > *lines)
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
Definition: lstmtrainer.h:268
bool load_from_file(const char *const filename, bool skip_fragments)
Definition: unicharset.h:348
bool LoadAllTrainingData(const GenericVector< STRING > &filenames)
bool LoadAllEvalData(const STRING &filenames_file)
Definition: lstmtester.cpp:30
int main(int argc, char **argv)
const char * c_str() const
Definition: strngs.cpp:209
STRING RunEvalAsync(int iteration, const double *training_errors, const GenericVector< char > &model_data, int training_stage)
Definition: lstmtester.cpp:52
void SaveRecognitionDump(GenericVector< char > *data) const