tesseract  4.00.00dev
lstmtraining.cpp File Reference
#include "commontraining.h"
#include "lstmtester.h"
#include "lstmtrainer.h"
#include "params.h"
#include "strngs.h"
#include "tprintf.h"
#include "unicharset_training_utils.h"

Go to the source code of this file.

Functions

 INT_PARAM_FLAG (debug_interval, 0, "How often to display the alignment.")
 
 STRING_PARAM_FLAG (net_spec, "", "Network specification")
 
 INT_PARAM_FLAG (net_mode, 192, "Controls network behavior.")
 
 INT_PARAM_FLAG (perfect_sample_delay, 0, "How many imperfect samples between perfect ones.")
 
 DOUBLE_PARAM_FLAG (target_error_rate, 0.01, "Final error rate in percent.")
 
 DOUBLE_PARAM_FLAG (weight_range, 0.1, "Range of initial random weights.")
 
 DOUBLE_PARAM_FLAG (learning_rate, 10.0e-4, "Weight factor for new deltas.")
 
 DOUBLE_PARAM_FLAG (momentum, 0.5, "Decay factor for repeating deltas.")
 
 DOUBLE_PARAM_FLAG (adam_beta, 0.999, "Decay factor for repeating deltas.")
 
 INT_PARAM_FLAG (max_image_MB, 6000, "Max memory to use for images.")
 
 STRING_PARAM_FLAG (continue_from, "", "Existing model to extend")
 
 STRING_PARAM_FLAG (model_output, "lstmtrain", "Basename for output models")
 
 STRING_PARAM_FLAG (train_listfile, "", "File listing training files in lstmf training format.")
 
 STRING_PARAM_FLAG (eval_listfile, "", "File listing eval files in lstmf training format.")
 
 BOOL_PARAM_FLAG (stop_training, false, "Just convert the training model to a runtime model.")
 
 BOOL_PARAM_FLAG (convert_to_int, false, "Convert the recognition model to an integer model.")
 
 BOOL_PARAM_FLAG (sequential_training, false, "Use the training files sequentially instead of round-robin.")
 
 INT_PARAM_FLAG (append_index, -1, "Index in continue_from Network at which to" " attach the new network defined by net_spec")
 
 BOOL_PARAM_FLAG (debug_network, false, "Get info on distribution of weight values")
 
 INT_PARAM_FLAG (max_iterations, 0, "If set, exit after this many iterations")
 
 STRING_PARAM_FLAG (traineddata, "", "Combined Dawgs/Unicharset/Recoder for language model")
 
 STRING_PARAM_FLAG (old_traineddata, "", "When changing the character set, this specifies the old" " character set that is to be replaced")
 
 BOOL_PARAM_FLAG (randomly_rotate, false, "Train OSD and randomly turn training samples upside-down")
 
int main (int argc, char **argv)
 

Variables

const int kNumPagesPerBatch = 100
 

Function Documentation

◆ BOOL_PARAM_FLAG() [1/5]

BOOL_PARAM_FLAG ( stop_training  ,
false  ,
"Just convert the training model to a runtime model."   
)

◆ BOOL_PARAM_FLAG() [2/5]

BOOL_PARAM_FLAG ( convert_to_int  ,
false  ,
"Convert the recognition model to an integer model."   
)

◆ BOOL_PARAM_FLAG() [3/5]

BOOL_PARAM_FLAG ( sequential_training  ,
false  ,
"Use the training files sequentially instead of round-robin."   
)

◆ BOOL_PARAM_FLAG() [4/5]

BOOL_PARAM_FLAG ( debug_network  ,
false  ,
"Get info on distribution of weight values"   
)

◆ BOOL_PARAM_FLAG() [5/5]

BOOL_PARAM_FLAG ( randomly_rotate  ,
false  ,
"Train OSD and randomly turn training samples upside-down"   
)

◆ DOUBLE_PARAM_FLAG() [1/5]

DOUBLE_PARAM_FLAG ( target_error_rate  ,
0.  01,
"Final error rate in percent."   
)

◆ DOUBLE_PARAM_FLAG() [2/5]

DOUBLE_PARAM_FLAG ( weight_range  ,
0.  1,
"Range of initial random weights."   
)

◆ DOUBLE_PARAM_FLAG() [3/5]

DOUBLE_PARAM_FLAG ( learning_rate  ,
10.0e-  4,
"Weight factor for new deltas."   
)

◆ DOUBLE_PARAM_FLAG() [4/5]

DOUBLE_PARAM_FLAG ( momentum  ,
0.  5,
"Decay factor for repeating deltas."   
)

◆ DOUBLE_PARAM_FLAG() [5/5]

DOUBLE_PARAM_FLAG ( adam_beta  ,
0.  999,
"Decay factor for repeating deltas."   
)

◆ INT_PARAM_FLAG() [1/6]

INT_PARAM_FLAG ( debug_interval  ,
,
"How often to display the alignment."   
)

◆ INT_PARAM_FLAG() [2/6]

INT_PARAM_FLAG ( net_mode  ,
192  ,
"Controls network behavior."   
)

◆ INT_PARAM_FLAG() [3/6]

INT_PARAM_FLAG ( perfect_sample_delay  ,
,
"How many imperfect samples between perfect ones."   
)

◆ INT_PARAM_FLAG() [4/6]

INT_PARAM_FLAG ( max_image_MB  ,
6000  ,
"Max memory to use for images."   
)

◆ INT_PARAM_FLAG() [5/6]

INT_PARAM_FLAG ( append_index  ,
1,
"Index in continue_from Network at which to" " attach the new network defined by net_spec"   
)

◆ INT_PARAM_FLAG() [6/6]

INT_PARAM_FLAG ( max_iterations  ,
,
"If  set,
exit after this many iterations"   
)

◆ main()

int main ( int  argc,
char **  argv 
)

This program reads in a text file consisting of feature samples from a training page in the following format:

   FontName UTF8-char-str xmin ymin xmax ymax page-number
    NumberOfFeatureTypes(N)
      FeatureTypeName1 NumberOfFeatures(M)
         Feature1
         ...
         FeatureM
      FeatureTypeName2 NumberOfFeatures(M)
         Feature1
         ...
         FeatureM
      ...
      FeatureTypeNameN NumberOfFeatures(M)
         Feature1
         ...
         FeatureM
   FontName CharName ...

The result of this program is a binary inttemp file used by the OCR engine.

Parameters
argcnumber of command line arguments
argvarray of command line arguments
Returns
none
Note
Exceptions: none
History: Fri Aug 18 08:56:17 1989, DSJ, Created.
History: Mon May 18 1998, Christy Russson, Revistion started.

Definition at line 73 of file lstmtraining.cpp.

73  {
74  ParseArguments(&argc, &argv);
75  // Purify the model name in case it is based on the network string.
76  if (FLAGS_model_output.empty()) {
77  tprintf("Must provide a --model_output!\n");
78  return 1;
79  }
80  if (FLAGS_traineddata.empty()) {
81  tprintf("Must provide a --traineddata see training wiki\n");
82  return 1;
83  }
84  STRING model_output = FLAGS_model_output.c_str();
85  for (int i = 0; i < model_output.length(); ++i) {
86  if (model_output[i] == '[' || model_output[i] == ']')
87  model_output[i] = '-';
88  if (model_output[i] == '(' || model_output[i] == ')')
89  model_output[i] = '_';
90  }
91  // Setup the trainer.
92  STRING checkpoint_file = FLAGS_model_output.c_str();
93  checkpoint_file += "_checkpoint";
94  STRING checkpoint_bak = checkpoint_file + ".bak";
95  tesseract::LSTMTrainer trainer(
96  nullptr, nullptr, nullptr, nullptr, FLAGS_model_output.c_str(),
97  checkpoint_file.c_str(), FLAGS_debug_interval,
98  static_cast<inT64>(FLAGS_max_image_MB) * 1048576);
99  trainer.InitCharSet(FLAGS_traineddata.c_str());
100 
101  // Reading something from an existing model doesn't require many flags,
102  // so do it now and exit.
103  if (FLAGS_stop_training || FLAGS_debug_network) {
104  if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(), nullptr)) {
105  tprintf("Failed to read continue from: %s\n",
106  FLAGS_continue_from.c_str());
107  return 1;
108  }
109  if (FLAGS_debug_network) {
110  trainer.DebugNetwork();
111  } else {
112  if (FLAGS_convert_to_int) trainer.ConvertToInt();
113  if (!trainer.SaveTraineddata(FLAGS_model_output.c_str())) {
114  tprintf("Failed to write recognition model : %s\n",
115  FLAGS_model_output.c_str());
116  }
117  }
118  return 0;
119  }
120 
121  // Get the list of files to process.
122  if (FLAGS_train_listfile.empty()) {
123  tprintf("Must supply a list of training filenames! --train_listfile\n");
124  return 1;
125  }
126  GenericVector<STRING> filenames;
127  if (!tesseract::LoadFileLinesToStrings(FLAGS_train_listfile.c_str(),
128  &filenames)) {
129  tprintf("Failed to load list of training filenames from %s\n",
130  FLAGS_train_listfile.c_str());
131  return 1;
132  }
133 
134  // Checkpoints always take priority if they are available.
135  if (trainer.TryLoadingCheckpoint(checkpoint_file.string(), nullptr) ||
136  trainer.TryLoadingCheckpoint(checkpoint_bak.string(), nullptr)) {
137  tprintf("Successfully restored trainer from %s\n",
138  checkpoint_file.string());
139  } else {
140  if (!FLAGS_continue_from.empty()) {
141  // Load a past model file to improve upon.
142  if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(),
143  FLAGS_append_index >= 0
144  ? FLAGS_continue_from.c_str()
145  : FLAGS_old_traineddata.c_str())) {
146  tprintf("Failed to continue from: %s\n", FLAGS_continue_from.c_str());
147  return 1;
148  }
149  tprintf("Continuing from %s\n", FLAGS_continue_from.c_str());
150  trainer.InitIterations();
151  }
152  if (FLAGS_continue_from.empty() || FLAGS_append_index >= 0) {
153  if (FLAGS_append_index >= 0) {
154  tprintf("Appending a new network to an old one!!");
155  if (FLAGS_continue_from.empty()) {
156  tprintf("Must set --continue_from for appending!\n");
157  return 1;
158  }
159  }
160  // We are initializing from scratch.
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  FLAGS_adam_beta)) {
165  tprintf("Failed to create network from spec: %s\n",
166  FLAGS_net_spec.c_str());
167  return 1;
168  }
169  trainer.set_perfect_delay(FLAGS_perfect_sample_delay);
170  }
171  }
172  if (!trainer.LoadAllTrainingData(filenames,
173  FLAGS_sequential_training
176  FLAGS_randomly_rotate)) {
177  tprintf("Load of images failed!!\n");
178  return 1;
179  }
180 
181  tesseract::LSTMTester tester(static_cast<inT64>(FLAGS_max_image_MB) *
182  1048576);
183  tesseract::TestCallback tester_callback = nullptr;
184  if (!FLAGS_eval_listfile.empty()) {
185  if (!tester.LoadAllEvalData(FLAGS_eval_listfile.c_str())) {
186  tprintf("Failed to load eval data from: %s\n",
187  FLAGS_eval_listfile.c_str());
188  return 1;
189  }
190  tester_callback =
192  }
193  do {
194  // Train a few.
195  int iteration = trainer.training_iteration();
196  for (int target_iteration = iteration + kNumPagesPerBatch;
197  iteration < target_iteration;
198  iteration = trainer.training_iteration()) {
199  trainer.TrainOnLine(&trainer, false);
200  }
201  STRING log_str;
202  trainer.MaintainCheckpoints(tester_callback, &log_str);
203  tprintf("%s\n", log_str.string());
204  } while (trainer.best_error_rate() > FLAGS_target_error_rate &&
205  (trainer.training_iteration() < FLAGS_max_iterations ||
206  FLAGS_max_iterations == 0));
207  delete tester_callback;
208  tprintf("Finished! Error rate = %g\n", trainer.best_error_rate());
209  return 0;
210 } /* main */
const int kNumPagesPerBatch
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
Definition: tesscallback.h:116
#define tprintf(...)
Definition: tprintf.h:31
const char * string() const
Definition: strngs.cpp:198
Definition: strngs.h:45
void ParseArguments(int *argc, char ***argv)
const char * c_str() const
Definition: strngs.cpp:209
bool LoadFileLinesToStrings(const STRING &filename, GenericVector< STRING > *lines)
int64_t inT64
Definition: host.h:40
STRING RunEvalAsync(int iteration, const double *training_errors, const TessdataManager &model_mgr, int training_stage)
Definition: lstmtester.cpp:52
inT32 length() const
Definition: strngs.cpp:193

◆ STRING_PARAM_FLAG() [1/7]

STRING_PARAM_FLAG ( net_spec  ,
""  ,
"Network specification"   
)

◆ STRING_PARAM_FLAG() [2/7]

STRING_PARAM_FLAG ( continue_from  ,
""  ,
"Existing model to extend"   
)

◆ STRING_PARAM_FLAG() [3/7]

STRING_PARAM_FLAG ( model_output  ,
"lstmtrain"  ,
"Basename for output models"   
)

◆ STRING_PARAM_FLAG() [4/7]

STRING_PARAM_FLAG ( train_listfile  ,
""  ,
"File listing training files in lstmf training format."   
)

◆ STRING_PARAM_FLAG() [5/7]

STRING_PARAM_FLAG ( eval_listfile  ,
""  ,
"File listing eval files in lstmf training format."   
)

◆ STRING_PARAM_FLAG() [6/7]

STRING_PARAM_FLAG ( traineddata  ,
""  ,
"Combined Dawgs/Unicharset/Recoder for language model"   
)

◆ STRING_PARAM_FLAG() [7/7]

STRING_PARAM_FLAG ( old_traineddata  ,
""  ,
"When changing the character  set,
this specifies the old" " character set that is to be replaced"   
)

Variable Documentation

◆ kNumPagesPerBatch

const int kNumPagesPerBatch = 100

Definition at line 67 of file lstmtraining.cpp.