tesseract  4.1.3
tesseract::LSTMTrainer Class Reference

#include <lstmtrainer.h>

Inheritance diagram for tesseract::LSTMTrainer:
tesseract::LSTMRecognizer

Public Member Functions

 LSTMTrainer ()
 
 LSTMTrainer (FileReader file_reader, FileWriter file_writer, CheckPointReader checkpoint_reader, CheckPointWriter checkpoint_writer, const char *model_base, const char *checkpoint_name, int debug_interval, int64_t max_memory)
 
virtual ~LSTMTrainer ()
 
bool TryLoadingCheckpoint (const char *filename, const char *old_traineddata)
 
void InitCharSet (const std::string &traineddata_path)
 
void InitCharSet (const TessdataManager &mgr)
 
bool InitNetwork (const STRING &network_spec, int append_index, int net_flags, float weight_range, float learning_rate, float momentum, float adam_beta)
 
int InitTensorFlowNetwork (const std::string &tf_proto)
 
void InitIterations ()
 
double ActivationError () const
 
double CharError () const
 
const double * error_rates () const
 
double best_error_rate () const
 
int best_iteration () const
 
int learning_iteration () const
 
int32_t improvement_steps () const
 
void set_perfect_delay (int delay)
 
const GenericVector< char > & best_trainer () const
 
double NewSingleError (ErrorTypes type) const
 
double LastSingleError (ErrorTypes type) const
 
const DocumentCachetraining_data () const
 
DocumentCachemutable_training_data ()
 
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)
 
void DebugNetwork ()
 
bool LoadAllTrainingData (const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, bool randomly_rotate)
 
bool MaintainCheckpoints (TestCallback tester, STRING *log_msg)
 
bool MaintainCheckpointsSpecific (int iteration, const GenericVector< char > *train_model, const GenericVector< char > *rec_model, TestCallback tester, STRING *log_msg)
 
void PrepareLogMsg (STRING *log_msg) const
 
void LogIterations (const char *intro_str, STRING *log_msg) const
 
bool TransitionTrainingStage (float error_threshold)
 
int CurrentTrainingStage () const
 
bool Serialize (SerializeAmount serialize_amount, const TessdataManager *mgr, TFile *fp) const
 
bool DeSerialize (const TessdataManager *mgr, TFile *fp)
 
void StartSubtrainer (STRING *log_msg)
 
SubTrainerResult UpdateSubtrainer (STRING *log_msg)
 
void ReduceLearningRates (LSTMTrainer *samples_trainer, STRING *log_msg)
 
int ReduceLayerLearningRates (double factor, int num_samples, LSTMTrainer *samples_trainer)
 
bool EncodeString (const STRING &str, GenericVector< int > *labels) const
 
const ImageDataTrainOnLine (LSTMTrainer *samples_trainer, bool batch)
 
Trainability TrainOnLine (const ImageData *trainingdata, bool batch)
 
Trainability PrepareForBackward (const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
 
bool SaveTrainingDump (SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const
 
bool ReadTrainingDump (const GenericVector< char > &data, LSTMTrainer *trainer) const
 
bool ReadSizedTrainingDump (const char *data, int size, LSTMTrainer *trainer) const
 
bool ReadLocalTrainingDump (const TessdataManager *mgr, const char *data, int size)
 
void SetupCheckpointInfo ()
 
bool SaveTraineddata (const STRING &filename)
 
void SaveRecognitionDump (GenericVector< char > *data) const
 
STRING DumpFilename () const
 
void FillErrorBuffer (double new_error, ErrorTypes type)
 
std::vector< int > MapRecoder (const UNICHARSET &old_chset, const UnicharCompress &old_recoder) const
 
- Public Member Functions inherited from tesseract::LSTMRecognizer
 LSTMRecognizer ()
 
 LSTMRecognizer (const STRING language_data_path_prefix)
 
 ~LSTMRecognizer ()
 
int NumOutputs () const
 
int training_iteration () const
 
int sample_iteration () const
 
double learning_rate () const
 
LossType OutputLossType () const
 
bool SimpleTextOutput () const
 
bool IsIntMode () const
 
bool IsRecoding () const
 
bool IsTensorFlow () const
 
GenericVector< STRINGEnumerateLayers () const
 
NetworkGetLayer (const STRING &id) const
 
float GetLayerLearningRate (const STRING &id) const
 
void ScaleLearningRate (double factor)
 
void ScaleLayerLearningRate (const STRING &id, double factor)
 
void ConvertToInt ()
 
const UNICHARSETGetUnicharset () const
 
const UnicharCompressGetRecoder () const
 
const DictGetDict () const
 
void SetIteration (int iteration)
 
int NumInputs () const
 
int null_char () const
 
bool Load (const ParamsVectors *params, const char *lang, TessdataManager *mgr)
 
bool Serialize (const TessdataManager *mgr, TFile *fp) const
 
bool DeSerialize (const TessdataManager *mgr, TFile *fp)
 
bool LoadCharsets (const TessdataManager *mgr)
 
bool LoadRecoder (TFile *fp)
 
bool LoadDictionary (const ParamsVectors *params, const char *lang, TessdataManager *mgr)
 
void RecognizeLine (const ImageData &image_data, bool invert, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words, int lstm_choice_mode=0)
 
void OutputStats (const NetworkIO &outputs, float *min_output, float *mean_output, float *sd)
 
bool RecognizeLine (const ImageData &image_data, bool invert, bool debug, bool re_invert, bool upside_down, float *scale_factor, NetworkIO *inputs, NetworkIO *outputs)
 
STRING DecodeLabels (const GenericVector< int > &labels)
 
void DisplayForward (const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
 
void LabelsFromOutputs (const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
 

Static Public Member Functions

static bool EncodeString (const STRING &str, const UNICHARSET &unicharset, const UnicharCompress *recoder, bool simple_text, int null_char, GenericVector< int > *labels)
 

Protected Member Functions

void InitCharSet ()
 
void SetNullChar ()
 
void EmptyConstructor ()
 
bool DebugLSTMTraining (const NetworkIO &inputs, const ImageData &trainingdata, const NetworkIO &fwd_outputs, const GenericVector< int > &truth_labels, const NetworkIO &outputs)
 
void DisplayTargets (const NetworkIO &targets, const char *window_name, ScrollView **window)
 
bool ComputeTextTargets (const NetworkIO &outputs, const GenericVector< int > &truth_labels, NetworkIO *targets)
 
bool ComputeCTCTargets (const GenericVector< int > &truth_labels, NetworkIO *outputs, NetworkIO *targets)
 
double ComputeErrorRates (const NetworkIO &deltas, double char_error, double word_error)
 
double ComputeRMSError (const NetworkIO &deltas)
 
double ComputeWinnerError (const NetworkIO &deltas)
 
double ComputeCharError (const GenericVector< int > &truth_str, const GenericVector< int > &ocr_str)
 
double ComputeWordError (STRING *truth_str, STRING *ocr_str)
 
void UpdateErrorBuffer (double new_error, ErrorTypes type)
 
void RollErrorBuffers ()
 
STRING UpdateErrorGraph (int iteration, double error_rate, const GenericVector< char > &model_data, TestCallback tester)
 
- Protected Member Functions inherited from tesseract::LSTMRecognizer
void SetRandomSeed ()
 
void DisplayLSTMOutput (const GenericVector< int > &labels, const GenericVector< int > &xcoords, int height, ScrollView *window)
 
void DebugActivationPath (const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
 
void DebugActivationRange (const NetworkIO &outputs, const char *label, int best_choice, int x_start, int x_end)
 
void LabelsViaReEncode (const NetworkIO &output, GenericVector< int > *labels, GenericVector< int > *xcoords)
 
void LabelsViaSimpleText (const NetworkIO &output, GenericVector< int > *labels, GenericVector< int > *xcoords)
 
const char * DecodeLabel (const GenericVector< int > &labels, int start, int *end, int *decoded)
 
const char * DecodeSingleLabel (int label)
 

Protected Attributes

ScrollViewalign_win_
 
ScrollViewtarget_win_
 
ScrollViewctc_win_
 
ScrollViewrecon_win_
 
int debug_interval_
 
int checkpoint_iteration_
 
STRING model_base_
 
STRING checkpoint_name_
 
bool randomly_rotate_
 
DocumentCache training_data_
 
STRING best_model_name_
 
int num_training_stages_
 
FileReader file_reader_
 
FileWriter file_writer_
 
CheckPointReader checkpoint_reader_
 
CheckPointWriter checkpoint_writer_
 
double best_error_rate_
 
double best_error_rates_ [ET_COUNT]
 
int best_iteration_
 
double worst_error_rate_
 
double worst_error_rates_ [ET_COUNT]
 
int worst_iteration_
 
int stall_iteration_
 
GenericVector< char > best_model_data_
 
GenericVector< char > worst_model_data_
 
GenericVector< char > best_trainer_
 
LSTMTrainersub_trainer_
 
float error_rate_of_last_saved_best_
 
int training_stage_
 
GenericVector< double > best_error_history_
 
GenericVector< int > best_error_iterations_
 
int32_t improvement_steps_
 
int learning_iteration_
 
int prev_sample_iteration_
 
int perfect_delay_
 
int last_perfect_training_iteration_
 
GenericVector< double > error_buffers_ [ET_COUNT]
 
double error_rates_ [ET_COUNT]
 
TessdataManager mgr_
 
- Protected Attributes inherited from tesseract::LSTMRecognizer
Networknetwork_
 
CCUtil ccutil_
 
UnicharCompress recoder_
 
STRING network_str_
 
int32_t training_flags_
 
int32_t training_iteration_
 
int32_t sample_iteration_
 
int32_t null_char_
 
float learning_rate_
 
float momentum_
 
float adam_beta_
 
TRand randomizer_
 
NetworkScratch scratch_space_
 
Dictdict_
 
RecodeBeamSearchsearch_
 
ScrollViewdebug_win_
 

Static Protected Attributes

static const int kRollingBufferSize_ = 1000
 

Detailed Description

Definition at line 89 of file lstmtrainer.h.

Constructor & Destructor Documentation

◆ LSTMTrainer() [1/2]

tesseract::LSTMTrainer::LSTMTrainer ( )

Definition at line 74 of file lstmtrainer.cpp.

75  : randomly_rotate_(false),
76  training_data_(0),
83  sub_trainer_(nullptr) {
85  debug_interval_ = 0;
86 }
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
Definition: lstmtrainer.h:291
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
CheckPointReader checkpoint_reader_
Definition: lstmtrainer.h:424
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
CheckPointWriter checkpoint_writer_
Definition: lstmtrainer.h:425
_ConstTessMemberResultCallback_5_0< false, R, T1, P1, P2, P3, P4, P5 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)(P1, P2, P3, P4, P5) const, typename Identity< P1 >::type p1, typename Identity< P2 >::type p2, typename Identity< P3 >::type p3, typename Identity< P4 >::type p4, typename Identity< P5 >::type p5)
Definition: tesscallback.h:258
DocumentCache training_data_
Definition: lstmtrainer.h:414
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const

◆ LSTMTrainer() [2/2]

tesseract::LSTMTrainer::LSTMTrainer ( FileReader  file_reader,
FileWriter  file_writer,
CheckPointReader  checkpoint_reader,
CheckPointWriter  checkpoint_writer,
const char *  model_base,
const char *  checkpoint_name,
int  debug_interval,
int64_t  max_memory 
)

Definition at line 88 of file lstmtrainer.cpp.

93  : randomly_rotate_(false),
94  training_data_(max_memory),
95  file_reader_(file_reader),
96  file_writer_(file_writer),
97  checkpoint_reader_(checkpoint_reader),
98  checkpoint_writer_(checkpoint_writer),
99  sub_trainer_(nullptr),
100  mgr_(file_reader) {
102  if (file_reader_ == nullptr) file_reader_ = LoadDataFromFile;
103  if (file_writer_ == nullptr) file_writer_ = SaveDataToFile;
104  if (checkpoint_reader_ == nullptr) {
107  }
108  if (checkpoint_writer_ == nullptr) {
111  }
112  debug_interval_ = debug_interval;
113  model_base_ = model_base;
114  checkpoint_name_ = checkpoint_name;
115 }
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
Definition: lstmtrainer.h:291
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
CheckPointReader checkpoint_reader_
Definition: lstmtrainer.h:424
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
CheckPointWriter checkpoint_writer_
Definition: lstmtrainer.h:425
TessdataManager mgr_
Definition: lstmtrainer.h:483
_ConstTessMemberResultCallback_5_0< false, R, T1, P1, P2, P3, P4, P5 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)(P1, P2, P3, P4, P5) const, typename Identity< P1 >::type p1, typename Identity< P2 >::type p2, typename Identity< P3 >::type p3, typename Identity< P4 >::type p4, typename Identity< P5 >::type p5)
Definition: tesscallback.h:258
DocumentCache training_data_
Definition: lstmtrainer.h:414
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const

◆ ~LSTMTrainer()

tesseract::LSTMTrainer::~LSTMTrainer ( )
virtual

Definition at line 117 of file lstmtrainer.cpp.

117  {
118  delete align_win_;
119  delete target_win_;
120  delete ctc_win_;
121  delete recon_win_;
122  delete checkpoint_reader_;
123  delete checkpoint_writer_;
124  delete sub_trainer_;
125 }
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
ScrollView * ctc_win_
Definition: lstmtrainer.h:401
CheckPointReader checkpoint_reader_
Definition: lstmtrainer.h:424
ScrollView * target_win_
Definition: lstmtrainer.h:399
CheckPointWriter checkpoint_writer_
Definition: lstmtrainer.h:425
ScrollView * recon_win_
Definition: lstmtrainer.h:403
ScrollView * align_win_
Definition: lstmtrainer.h:397

Member Function Documentation

◆ ActivationError()

double tesseract::LSTMTrainer::ActivationError ( ) const
inline

Definition at line 136 of file lstmtrainer.h.

136  {
137  return error_rates_[ET_DELTA];
138  }
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481

◆ best_error_rate()

double tesseract::LSTMTrainer::best_error_rate ( ) const
inline

Definition at line 143 of file lstmtrainer.h.

143  {
144  return best_error_rate_;
145  }

◆ best_iteration()

int tesseract::LSTMTrainer::best_iteration ( ) const
inline

Definition at line 146 of file lstmtrainer.h.

146  {
147  return best_iteration_;
148  }

◆ best_trainer()

const GenericVector<char>& tesseract::LSTMTrainer::best_trainer ( ) const
inline

Definition at line 152 of file lstmtrainer.h.

152 { return best_trainer_; }
GenericVector< char > best_trainer_
Definition: lstmtrainer.h:447

◆ CharError()

double tesseract::LSTMTrainer::CharError ( ) const
inline

Definition at line 139 of file lstmtrainer.h.

◆ ComputeCharError()

double tesseract::LSTMTrainer::ComputeCharError ( const GenericVector< int > &  truth_str,
const GenericVector< int > &  ocr_str 
)
protected

Definition at line 1195 of file lstmtrainer.cpp.

1196  {
1197  GenericVector<int> label_counts;
1198  label_counts.init_to_size(NumOutputs(), 0);
1199  int truth_size = 0;
1200  for (int i = 0; i < truth_str.size(); ++i) {
1201  if (truth_str[i] != null_char_) {
1202  ++label_counts[truth_str[i]];
1203  ++truth_size;
1204  }
1205  }
1206  for (int i = 0; i < ocr_str.size(); ++i) {
1207  if (ocr_str[i] != null_char_) {
1208  --label_counts[ocr_str[i]];
1209  }
1210  }
1211  int char_errors = 0;
1212  for (int i = 0; i < label_counts.size(); ++i) {
1213  char_errors += abs(label_counts[i]);
1214  }
1215  if (truth_size == 0) {
1216  return (char_errors == 0) ? 0.0 : 1.0;
1217  }
1218  return static_cast<double>(char_errors) / truth_size;
1219 }
void init_to_size(int size, const T &t)
int size() const
Definition: genericvector.h:72

◆ ComputeCTCTargets()

bool tesseract::LSTMTrainer::ComputeCTCTargets ( const GenericVector< int > &  truth_labels,
NetworkIO outputs,
NetworkIO targets 
)
protected

Definition at line 1127 of file lstmtrainer.cpp.

1128  {
1129  // Bottom-clip outputs to a minimum probability.
1130  CTC::NormalizeProbs(outputs);
1131  return CTC::ComputeCTCTargets(truth_labels, null_char_,
1132  outputs->float_array(), targets);
1133 }
static void NormalizeProbs(NetworkIO *probs)
Definition: ctc.h:36
static bool ComputeCTCTargets(const GenericVector< int > &truth_labels, int null_char, const GENERIC_2D_ARRAY< float > &outputs, NetworkIO *targets)
Definition: ctc.cpp:54

◆ ComputeErrorRates()

double tesseract::LSTMTrainer::ComputeErrorRates ( const NetworkIO deltas,
double  char_error,
double  word_error 
)
protected

Definition at line 1138 of file lstmtrainer.cpp.

1139  {
1141  // Delta error is the fraction of timesteps with >0.5 error in the top choice
1142  // score. If zero, then the top choice characters are guaranteed correct,
1143  // even when there is residue in the RMS error.
1144  double delta_error = ComputeWinnerError(deltas);
1145  UpdateErrorBuffer(delta_error, ET_DELTA);
1146  UpdateErrorBuffer(word_error, ET_WORD_RECERR);
1147  UpdateErrorBuffer(char_error, ET_CHAR_ERROR);
1148  // Skip ratio measures the difference between sample_iteration_ and
1149  // training_iteration_, which reflects the number of unusable samples,
1150  // usually due to unencodable truth text, or the text not fitting in the
1151  // space for the output.
1152  double skip_count = sample_iteration_ - prev_sample_iteration_;
1153  UpdateErrorBuffer(skip_count, ET_SKIP_RATIO);
1154  return delta_error;
1155 }
void UpdateErrorBuffer(double new_error, ErrorTypes type)
double ComputeRMSError(const NetworkIO &deltas)
double ComputeWinnerError(const NetworkIO &deltas)

◆ ComputeRMSError()

double tesseract::LSTMTrainer::ComputeRMSError ( const NetworkIO deltas)
protected

Definition at line 1158 of file lstmtrainer.cpp.

1158  {
1159  double total_error = 0.0;
1160  int width = deltas.Width();
1161  int num_classes = deltas.NumFeatures();
1162  for (int t = 0; t < width; ++t) {
1163  const float* class_errs = deltas.f(t);
1164  for (int c = 0; c < num_classes; ++c) {
1165  double error = class_errs[c];
1166  total_error += error * error;
1167  }
1168  }
1169  return sqrt(total_error / (width * num_classes));
1170 }

◆ ComputeTextTargets()

bool tesseract::LSTMTrainer::ComputeTextTargets ( const NetworkIO outputs,
const GenericVector< int > &  truth_labels,
NetworkIO targets 
)
protected

Definition at line 1107 of file lstmtrainer.cpp.

1109  {
1110  if (truth_labels.size() > targets->Width()) {
1111  tprintf("Error: transcription %s too long to fit into target of width %d\n",
1112  DecodeLabels(truth_labels).string(), targets->Width());
1113  return false;
1114  }
1115  for (int i = 0; i < truth_labels.size() && i < targets->Width(); ++i) {
1116  targets->SetActivations(i, truth_labels[i], 1.0);
1117  }
1118  for (int i = truth_labels.size(); i < targets->Width(); ++i) {
1119  targets->SetActivations(i, null_char_, 1.0);
1120  }
1121  return true;
1122 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
STRING DecodeLabels(const GenericVector< int > &labels)
int size() const
Definition: genericvector.h:72

◆ ComputeWinnerError()

double tesseract::LSTMTrainer::ComputeWinnerError ( const NetworkIO deltas)
protected

Definition at line 1177 of file lstmtrainer.cpp.

1177  {
1178  int num_errors = 0;
1179  int width = deltas.Width();
1180  int num_classes = deltas.NumFeatures();
1181  for (int t = 0; t < width; ++t) {
1182  const float* class_errs = deltas.f(t);
1183  for (int c = 0; c < num_classes; ++c) {
1184  float abs_delta = fabs(class_errs[c]);
1185  // TODO(rays) Filtering cases where the delta is very large to cut out
1186  // GT errors doesn't work. Find a better way or get better truth.
1187  if (0.5 <= abs_delta)
1188  ++num_errors;
1189  }
1190  }
1191  return static_cast<double>(num_errors) / width;
1192 }

◆ ComputeWordError()

double tesseract::LSTMTrainer::ComputeWordError ( STRING truth_str,
STRING ocr_str 
)
protected

Definition at line 1223 of file lstmtrainer.cpp.

1223  {
1224  using StrMap = std::unordered_map<std::string, int, std::hash<std::string>>;
1225  GenericVector<STRING> truth_words, ocr_words;
1226  truth_str->split(' ', &truth_words);
1227  if (truth_words.empty()) return 0.0;
1228  ocr_str->split(' ', &ocr_words);
1229  StrMap word_counts;
1230  for (int i = 0; i < truth_words.size(); ++i) {
1231  std::string truth_word(truth_words[i].string());
1232  auto it = word_counts.find(truth_word);
1233  if (it == word_counts.end())
1234  word_counts.insert(std::make_pair(truth_word, 1));
1235  else
1236  ++it->second;
1237  }
1238  for (int i = 0; i < ocr_words.size(); ++i) {
1239  std::string ocr_word(ocr_words[i].string());
1240  auto it = word_counts.find(ocr_word);
1241  if (it == word_counts.end())
1242  word_counts.insert(std::make_pair(ocr_word, -1));
1243  else
1244  --it->second;
1245  }
1246  int word_recall_errs = 0;
1247  for (StrMap::const_iterator it = word_counts.begin(); it != word_counts.end();
1248  ++it) {
1249  if (it->second > 0) word_recall_errs += it->second;
1250  }
1251  return static_cast<double>(word_recall_errs) / truth_words.size();
1252 }
bool empty() const
Definition: genericvector.h:91
void split(char c, GenericVector< STRING > *splited)
Definition: strngs.cpp:282
int size() const
Definition: genericvector.h:72

◆ CurrentTrainingStage()

int tesseract::LSTMTrainer::CurrentTrainingStage ( ) const
inline

Definition at line 211 of file lstmtrainer.h.

211 { return training_stage_; }

◆ DebugLSTMTraining()

bool tesseract::LSTMTrainer::DebugLSTMTraining ( const NetworkIO inputs,
const ImageData trainingdata,
const NetworkIO fwd_outputs,
const GenericVector< int > &  truth_labels,
const NetworkIO outputs 
)
protected

Definition at line 1033 of file lstmtrainer.cpp.

1037  {
1038  const STRING& truth_text = DecodeLabels(truth_labels);
1039  if (truth_text.string() == nullptr || truth_text.length() <= 0) {
1040  tprintf("Empty truth string at decode time!\n");
1041  return false;
1042  }
1043  if (debug_interval_ != 0) {
1044  // Get class labels, xcoords and string.
1045  GenericVector<int> labels;
1046  GenericVector<int> xcoords;
1047  LabelsFromOutputs(outputs, &labels, &xcoords);
1048  STRING text = DecodeLabels(labels);
1049  tprintf("Iteration %d: GROUND TRUTH : %s\n",
1050  training_iteration(), truth_text.string());
1051  if (truth_text != text) {
1052  tprintf("Iteration %d: ALIGNED TRUTH : %s\n",
1053  training_iteration(), text.string());
1054  }
1055  if (debug_interval_ > 0 && training_iteration() % debug_interval_ == 0) {
1056  tprintf("TRAINING activation path for truth string %s\n",
1057  truth_text.string());
1058  DebugActivationPath(outputs, labels, xcoords);
1059  DisplayForward(inputs, labels, xcoords, "LSTMTraining", &align_win_);
1060  if (OutputLossType() == LT_CTC) {
1061  DisplayTargets(fwd_outputs, "CTC Outputs", &ctc_win_);
1062  DisplayTargets(outputs, "CTC Targets", &target_win_);
1063  }
1064  }
1065  }
1066  return true;
1067 }
LossType OutputLossType() const
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
ScrollView * ctc_win_
Definition: lstmtrainer.h:401
ScrollView * target_win_
Definition: lstmtrainer.h:399
const char * string() const
Definition: strngs.cpp:194
void DisplayForward(const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
void DisplayTargets(const NetworkIO &targets, const char *window_name, ScrollView **window)
int32_t length() const
Definition: strngs.cpp:189
STRING DecodeLabels(const GenericVector< int > &labels)
void DebugActivationPath(const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
Definition: strngs.h:45
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
ScrollView * align_win_
Definition: lstmtrainer.h:397

◆ DebugNetwork()

void tesseract::LSTMTrainer::DebugNetwork ( )

Definition at line 295 of file lstmtrainer.cpp.

295  {
297 }
virtual void DebugWeights()=0

◆ DeSerialize()

bool tesseract::LSTMTrainer::DeSerialize ( const TessdataManager mgr,
TFile fp 
)

Definition at line 470 of file lstmtrainer.cpp.

470  {
471  if (!LSTMRecognizer::DeSerialize(mgr, fp)) return false;
472  if (!fp->DeSerialize(&learning_iteration_)) {
473  // Special case. If we successfully decoded the recognizer, but fail here
474  // then it means we were just given a recognizer, so issue a warning and
475  // allow it.
476  tprintf("Warning: LSTMTrainer deserialized an LSTMRecognizer!\n");
479  return true;
480  }
481  if (!fp->DeSerialize(&prev_sample_iteration_)) return false;
482  if (!fp->DeSerialize(&perfect_delay_)) return false;
483  if (!fp->DeSerialize(&last_perfect_training_iteration_)) return false;
484  for (auto & error_buffer : error_buffers_) {
485  if (!error_buffer.DeSerialize(fp)) return false;
486  }
487  if (!fp->DeSerialize(&error_rates_[0], countof(error_rates_))) return false;
488  if (!fp->DeSerialize(&training_stage_)) return false;
489  uint8_t amount;
490  if (!fp->DeSerialize(&amount)) return false;
491  if (amount == LIGHT) return true; // Don't read the rest.
492  if (!fp->DeSerialize(&best_error_rate_)) return false;
493  if (!fp->DeSerialize(&best_error_rates_[0], countof(best_error_rates_))) return false;
494  if (!fp->DeSerialize(&best_iteration_)) return false;
495  if (!fp->DeSerialize(&worst_error_rate_)) return false;
496  if (!fp->DeSerialize(&worst_error_rates_[0], countof(worst_error_rates_))) return false;
497  if (!fp->DeSerialize(&worst_iteration_)) return false;
498  if (!fp->DeSerialize(&stall_iteration_)) return false;
499  if (!best_model_data_.DeSerialize(fp)) return false;
500  if (!worst_model_data_.DeSerialize(fp)) return false;
501  if (amount != NO_BEST_TRAINER && !best_trainer_.DeSerialize(fp)) return false;
502  GenericVector<char> sub_data;
503  if (!sub_data.DeSerialize(fp)) return false;
504  delete sub_trainer_;
505  if (sub_data.empty()) {
506  sub_trainer_ = nullptr;
507  } else {
508  sub_trainer_ = new LSTMTrainer();
509  if (!ReadTrainingDump(sub_data, sub_trainer_)) return false;
510  }
511  if (!best_error_history_.DeSerialize(fp)) return false;
512  if (!best_error_iterations_.DeSerialize(fp)) return false;
513  return fp->DeSerialize(&improvement_steps_);
514 }
bool empty() const
Definition: genericvector.h:91
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
Definition: lstmtrainer.h:291
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
GenericVector< int > best_error_iterations_
Definition: lstmtrainer.h:458
GenericVector< char > worst_model_data_
Definition: lstmtrainer.h:445
double best_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:432
GenericVector< double > best_error_history_
Definition: lstmtrainer.h:457
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
constexpr size_t countof(T const (&)[N]) noexcept
Definition: serialis.h:43
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
bool DeSerialize(bool swap, FILE *fp)
double worst_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:438
GenericVector< char > best_model_data_
Definition: lstmtrainer.h:444
GenericVector< char > best_trainer_
Definition: lstmtrainer.h:447
virtual void SetEnableTraining(TrainingState state)
Definition: network.cpp:110
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479

◆ DisplayTargets()

void tesseract::LSTMTrainer::DisplayTargets ( const NetworkIO targets,
const char *  window_name,
ScrollView **  window 
)
protected

Definition at line 1070 of file lstmtrainer.cpp.

1071  {
1072 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics.
1073  int width = targets.Width();
1074  int num_features = targets.NumFeatures();
1075  Network::ClearWindow(true, window_name, width * kTargetXScale, kTargetYScale,
1076  window);
1077  for (int c = 0; c < num_features; ++c) {
1078  int color = c % (ScrollView::GREEN_YELLOW - 1) + 2;
1079  (*window)->Pen(static_cast<ScrollView::Color>(color));
1080  int start_t = -1;
1081  for (int t = 0; t < width; ++t) {
1082  double target = targets.f(t)[c];
1083  target *= kTargetYScale;
1084  if (target >= 1) {
1085  if (start_t < 0) {
1086  (*window)->SetCursor(t - 1, 0);
1087  start_t = t;
1088  }
1089  (*window)->DrawTo(t, target);
1090  } else if (start_t >= 0) {
1091  (*window)->DrawTo(t, 0);
1092  (*window)->DrawTo(start_t - 1, 0);
1093  start_t = -1;
1094  }
1095  }
1096  if (start_t >= 0) {
1097  (*window)->DrawTo(width, 0);
1098  (*window)->DrawTo(start_t - 1, 0);
1099  }
1100  }
1101  (*window)->Update();
1102 #endif // GRAPHICS_DISABLED
1103 }
const int kTargetYScale
Definition: lstmtrainer.cpp:72
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
Definition: network.cpp:312
const int kTargetXScale
Definition: lstmtrainer.cpp:71

◆ DumpFilename()

STRING tesseract::LSTMTrainer::DumpFilename ( ) const

Definition at line 944 of file lstmtrainer.cpp.

944  {
945  STRING filename;
947  filename.add_str_int("_", best_iteration_);
948  filename += ".checkpoint";
949  return filename;
950 }
const char * string() const
Definition: strngs.cpp:194
void add_str_int(const char *str, int number)
Definition: strngs.cpp:377
Definition: strngs.h:45
void add_str_double(const char *str, double number)
Definition: strngs.cpp:387

◆ EmptyConstructor()

void tesseract::LSTMTrainer::EmptyConstructor ( )
protected

Definition at line 1018 of file lstmtrainer.cpp.

1018  {
1019  align_win_ = nullptr;
1020  target_win_ = nullptr;
1021  ctc_win_ = nullptr;
1022  recon_win_ = nullptr;
1024  training_stage_ = 0;
1026  InitIterations();
1027 }
ScrollView * ctc_win_
Definition: lstmtrainer.h:401
ScrollView * target_win_
Definition: lstmtrainer.h:399
ScrollView * recon_win_
Definition: lstmtrainer.h:403
ScrollView * align_win_
Definition: lstmtrainer.h:397

◆ EncodeString() [1/2]

bool tesseract::LSTMTrainer::EncodeString ( const STRING str,
GenericVector< int > *  labels 
) const
inline

Definition at line 246 of file lstmtrainer.h.

246  {
247  return EncodeString(str, GetUnicharset(), IsRecoding() ? &recoder_ : nullptr,
248  SimpleTextOutput(), null_char_, labels);
249  }
const UNICHARSET & GetUnicharset() const
bool EncodeString(const STRING &str, GenericVector< int > *labels) const
Definition: lstmtrainer.h:246

◆ EncodeString() [2/2]

bool tesseract::LSTMTrainer::EncodeString ( const STRING str,
const UNICHARSET unicharset,
const UnicharCompress recoder,
bool  simple_text,
int  null_char,
GenericVector< int > *  labels 
)
static

Definition at line 720 of file lstmtrainer.cpp.

722  {
723  if (str.string() == nullptr || str.length() <= 0) {
724  tprintf("Empty truth string!\n");
725  return false;
726  }
727  int err_index;
728  GenericVector<int> internal_labels;
729  labels->truncate(0);
730  if (!simple_text) labels->push_back(null_char);
731  std::string cleaned = unicharset.CleanupString(str.string());
732  if (unicharset.encode_string(cleaned.c_str(), true, &internal_labels, nullptr,
733  &err_index)) {
734  bool success = true;
735  for (int i = 0; i < internal_labels.size(); ++i) {
736  if (recoder != nullptr) {
737  // Re-encode labels via recoder.
738  RecodedCharID code;
739  int len = recoder->EncodeUnichar(internal_labels[i], &code);
740  if (len > 0) {
741  for (int j = 0; j < len; ++j) {
742  labels->push_back(code(j));
743  if (!simple_text) labels->push_back(null_char);
744  }
745  } else {
746  success = false;
747  err_index = 0;
748  break;
749  }
750  } else {
751  labels->push_back(internal_labels[i]);
752  if (!simple_text) labels->push_back(null_char);
753  }
754  }
755  if (success) return true;
756  }
757  tprintf("Encoding of string failed! Failure bytes:");
758  while (err_index < cleaned.size()) {
759  tprintf(" %x", cleaned[err_index++]);
760  }
761  tprintf("\n");
762  return false;
763 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
const char * string() const
Definition: strngs.cpp:194
void truncate(int size)
int32_t length() const
Definition: strngs.cpp:189
int push_back(T object)
static std::string CleanupString(const char *utf8_str)
Definition: unicharset.h:246
int size() const
Definition: genericvector.h:72
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:259

◆ error_rates()

const double* tesseract::LSTMTrainer::error_rates ( ) const
inline

Definition at line 140 of file lstmtrainer.h.

140  {
141  return error_rates_;
142  }
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481

◆ FillErrorBuffer()

void tesseract::LSTMTrainer::FillErrorBuffer ( double  new_error,
ErrorTypes  type 
)

Definition at line 953 of file lstmtrainer.cpp.

953  {
954  for (int i = 0; i < kRollingBufferSize_; ++i)
955  error_buffers_[type][i] = new_error;
956  error_rates_[type] = 100.0 * new_error;
957 }
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
static const int kRollingBufferSize_
Definition: lstmtrainer.h:478
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479

◆ GridSearchDictParams()

Trainability tesseract::LSTMTrainer::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 
)

Definition at line 245 of file lstmtrainer.cpp.

248  {
249  sample_iteration_ = iteration;
250  NetworkIO fwd_outputs, targets;
251  Trainability result =
252  PrepareForBackward(trainingdata, &fwd_outputs, &targets);
253  if (result == UNENCODABLE || result == HI_PRECISION_ERR || dict_ == nullptr)
254  return result;
255 
256  // Encode/decode the truth to get the normalization.
257  GenericVector<int> truth_labels, ocr_labels, xcoords;
258  ASSERT_HOST(EncodeString(trainingdata->transcription(), &truth_labels));
259  // NO-dict error.
260  RecodeBeamSearch base_search(recoder_, null_char_, SimpleTextOutput(), nullptr);
261  base_search.Decode(fwd_outputs, 1.0, 0.0, RecodeBeamSearch::kMinCertainty,
262  nullptr);
263  base_search.ExtractBestPathAsLabels(&ocr_labels, &xcoords);
264  STRING truth_text = DecodeLabels(truth_labels);
265  STRING ocr_text = DecodeLabels(ocr_labels);
266  double baseline_error = ComputeWordError(&truth_text, &ocr_text);
267  results->add_str_double("0,0=", baseline_error);
268 
269  RecodeBeamSearch search(recoder_, null_char_, SimpleTextOutput(), dict_);
270  for (double r = min_dict_ratio; r < max_dict_ratio; r += dict_ratio_step) {
271  for (double c = min_cert_offset; c < max_cert_offset;
272  c += cert_offset_step) {
273  search.Decode(fwd_outputs, r, c, RecodeBeamSearch::kMinCertainty, nullptr);
274  search.ExtractBestPathAsLabels(&ocr_labels, &xcoords);
275  truth_text = DecodeLabels(truth_labels);
276  ocr_text = DecodeLabels(ocr_labels);
277  // This is destructive on both strings.
278  double word_error = ComputeWordError(&truth_text, &ocr_text);
279  if ((r == min_dict_ratio && c == min_cert_offset) ||
280  !std::isfinite(word_error)) {
281  STRING t = DecodeLabels(truth_labels);
282  STRING o = DecodeLabels(ocr_labels);
283  tprintf("r=%g, c=%g, truth=%s, ocr=%s, wderr=%g, truth[0]=%d\n", r, c,
284  t.string(), o.string(), word_error, truth_labels[0]);
285  }
286  results->add_str_double(" ", r);
287  results->add_str_double(",", c);
288  results->add_str_double("=", word_error);
289  }
290  }
291  return result;
292 }
LIST search(LIST list, void *key, int_compare is_equal)
Definition: oldlist.cpp:258
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
static constexpr float kMinCertainty
Definition: recodebeam.h:222
const char * string() const
Definition: strngs.cpp:194
STRING DecodeLabels(const GenericVector< int > &labels)
bool EncodeString(const STRING &str, GenericVector< int > *labels) const
Definition: lstmtrainer.h:246
Definition: strngs.h:45
double ComputeWordError(STRING *truth_str, STRING *ocr_str)
void add_str_double(const char *str, double number)
Definition: strngs.cpp:387
#define ASSERT_HOST(x)
Definition: errcode.h:88

◆ improvement_steps()

int32_t tesseract::LSTMTrainer::improvement_steps ( ) const
inline

Definition at line 150 of file lstmtrainer.h.

150 { return improvement_steps_; }

◆ InitCharSet() [1/3]

void tesseract::LSTMTrainer::InitCharSet ( const std::string &  traineddata_path)
inline

Definition at line 109 of file lstmtrainer.h.

109  {
110  ASSERT_HOST(mgr_.Init(traineddata_path.c_str()));
111  InitCharSet();
112  }
bool Init(const char *data_file_name)
TessdataManager mgr_
Definition: lstmtrainer.h:483
#define ASSERT_HOST(x)
Definition: errcode.h:88

◆ InitCharSet() [2/3]

void tesseract::LSTMTrainer::InitCharSet ( const TessdataManager mgr)
inline

Definition at line 113 of file lstmtrainer.h.

113  {
114  mgr_ = mgr;
115  InitCharSet();
116  }
TessdataManager mgr_
Definition: lstmtrainer.h:483

◆ InitCharSet() [3/3]

void tesseract::LSTMTrainer::InitCharSet ( )
protected

Definition at line 996 of file lstmtrainer.cpp.

996  {
999  // Initialize the unicharset and recoder.
1000  if (!LoadCharsets(&mgr_)) {
1001  ASSERT_HOST(
1002  "Must provide a traineddata containing lstm_unicharset and"
1003  " lstm_recoder!\n" != nullptr);
1004  }
1005  SetNullChar();
1006 }
bool LoadCharsets(const TessdataManager *mgr)
TessdataManager mgr_
Definition: lstmtrainer.h:483
#define ASSERT_HOST(x)
Definition: errcode.h:88

◆ InitIterations()

void tesseract::LSTMTrainer::InitIterations ( )

Definition at line 220 of file lstmtrainer.cpp.

220  {
221  sample_iteration_ = 0;
225  best_error_rate_ = 100.0;
226  best_iteration_ = 0;
227  worst_error_rate_ = 0.0;
228  worst_iteration_ = 0;
231  perfect_delay_ = 0;
233  for (int i = 0; i < ET_COUNT; ++i) {
234  best_error_rates_[i] = 100.0;
235  worst_error_rates_[i] = 0.0;
237  error_rates_[i] = 100.0;
238  }
240 }
void init_to_size(int size, const T &t)
const int kMinStartedErrorRate
Definition: lstmtrainer.cpp:61
double best_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:432
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
double worst_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:438
static const int kRollingBufferSize_
Definition: lstmtrainer.h:478
const int kMinStallIterations
Definition: lstmtrainer.cpp:48
float error_rate_of_last_saved_best_
Definition: lstmtrainer.h:452
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479

◆ InitNetwork()

bool tesseract::LSTMTrainer::InitNetwork ( const STRING network_spec,
int  append_index,
int  net_flags,
float  weight_range,
float  learning_rate,
float  momentum,
float  adam_beta 
)

Definition at line 176 of file lstmtrainer.cpp.

179  {
180  mgr_.SetVersionString(mgr_.VersionString() + ":" + network_spec.string());
181  adam_beta_ = adam_beta;
183  momentum_ = momentum;
184  SetNullChar();
185  if (!NetworkBuilder::InitNetwork(recoder_.code_range(), network_spec,
186  append_index, net_flags, weight_range,
187  &randomizer_, &network_)) {
188  return false;
189  }
190  network_str_ += network_spec;
191  tprintf("Built network:%s from request %s\n",
192  network_->spec().string(), network_spec.string());
193  tprintf(
194  "Training parameters:\n Debug interval = %d,"
195  " weights = %g, learning rate = %g, momentum=%g\n",
196  debug_interval_, weight_range, learning_rate_, momentum_);
197  tprintf("null char=%d\n", null_char_);
198  return true;
199 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
std::string VersionString() const
virtual STRING spec() const
Definition: network.h:141
const char * string() const
Definition: strngs.cpp:194
static bool InitNetwork(int num_outputs, STRING network_spec, int append_index, int net_flags, float weight_range, TRand *randomizer, Network **network)
TessdataManager mgr_
Definition: lstmtrainer.h:483
void SetVersionString(const std::string &v_str)
double learning_rate() const

◆ InitTensorFlowNetwork()

int tesseract::LSTMTrainer::InitTensorFlowNetwork ( const std::string &  tf_proto)

◆ LastSingleError()

double tesseract::LSTMTrainer::LastSingleError ( ErrorTypes  type) const
inline

Definition at line 160 of file lstmtrainer.h.

160  {
161  return error_buffers_[type]
164  }
static const int kRollingBufferSize_
Definition: lstmtrainer.h:478
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479

◆ learning_iteration()

int tesseract::LSTMTrainer::learning_iteration ( ) const
inline

Definition at line 149 of file lstmtrainer.h.

149 { return learning_iteration_; }

◆ LoadAllTrainingData()

bool tesseract::LSTMTrainer::LoadAllTrainingData ( const GenericVector< STRING > &  filenames,
CachingStrategy  cache_strategy,
bool  randomly_rotate 
)

Definition at line 302 of file lstmtrainer.cpp.

304  {
305  randomly_rotate_ = randomly_rotate;
307  return training_data_.LoadDocuments(filenames, cache_strategy, file_reader_);
308 }
bool LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)
Definition: imagedata.cpp:580
DocumentCache training_data_
Definition: lstmtrainer.h:414

◆ LogIterations()

void tesseract::LSTMTrainer::LogIterations ( const char *  intro_str,
STRING log_msg 
) const

Definition at line 414 of file lstmtrainer.cpp.

414  {
415  *log_msg += intro_str;
416  log_msg->add_str_int(" iteration ", learning_iteration());
417  log_msg->add_str_int("/", training_iteration());
418  log_msg->add_str_int("/", sample_iteration());
419 }
int learning_iteration() const
Definition: lstmtrainer.h:149
void add_str_int(const char *str, int number)
Definition: strngs.cpp:377

◆ MaintainCheckpoints()

bool tesseract::LSTMTrainer::MaintainCheckpoints ( TestCallback  tester,
STRING log_msg 
)

Definition at line 314 of file lstmtrainer.cpp.

314  {
315  PrepareLogMsg(log_msg);
316  double error_rate = CharError();
317  int iteration = learning_iteration();
318  if (iteration >= stall_iteration_ &&
319  error_rate > best_error_rate_ * (1.0 + kSubTrainerMarginFraction) &&
321  // It hasn't got any better in a long while, and is a margin worse than the
322  // best, so go back to the best model and try a different learning rate.
323  StartSubtrainer(log_msg);
324  }
325  SubTrainerResult sub_trainer_result = STR_NONE;
326  if (sub_trainer_ != nullptr) {
327  sub_trainer_result = UpdateSubtrainer(log_msg);
328  if (sub_trainer_result == STR_REPLACED) {
329  // Reset the inputs, as we have overwritten *this.
330  error_rate = CharError();
331  iteration = learning_iteration();
332  PrepareLogMsg(log_msg);
333  }
334  }
335  bool result = true; // Something interesting happened.
336  GenericVector<char> rec_model_data;
337  if (error_rate < best_error_rate_) {
338  SaveRecognitionDump(&rec_model_data);
339  log_msg->add_str_double(" New best char error = ", error_rate);
340  *log_msg += UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
341  // If sub_trainer_ is not nullptr, either *this beat it to a new best, or it
342  // just overwrote *this. In either case, we have finished with it.
343  delete sub_trainer_;
344  sub_trainer_ = nullptr;
347  log_msg->add_str_int(" Transitioned to stage ", CurrentTrainingStage());
348  }
351  STRING best_model_name = DumpFilename();
352  if (!(*file_writer_)(best_trainer_, best_model_name.c_str())) {
353  *log_msg += " failed to write best model:";
354  } else {
355  *log_msg += " wrote best model:";
357  }
358  *log_msg += best_model_name;
359  }
360  } else if (error_rate > worst_error_rate_) {
361  SaveRecognitionDump(&rec_model_data);
362  log_msg->add_str_double(" New worst char error = ", error_rate);
363  *log_msg += UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
366  // Error rate has ballooned. Go back to the best model.
367  *log_msg += "\nDivergence! ";
368  // Copy best_trainer_ before reading it, as it will get overwritten.
369  GenericVector<char> revert_data(best_trainer_);
370  if (checkpoint_reader_->Run(revert_data, this)) {
371  LogIterations("Reverted to", log_msg);
372  ReduceLearningRates(this, log_msg);
373  } else {
374  LogIterations("Failed to Revert at", log_msg);
375  }
376  // If it fails again, we will wait twice as long before reverting again.
377  stall_iteration_ = iteration + 2 * (iteration - learning_iteration());
378  // Re-save the best trainer with the new learning rates and stall
379  // iteration.
381  }
382  } else {
383  // Something interesting happened only if the sub_trainer_ was trained.
384  result = sub_trainer_result != STR_NONE;
385  }
386  if (checkpoint_writer_ != nullptr && file_writer_ != nullptr &&
387  checkpoint_name_.length() > 0) {
388  // Write a current checkpoint.
389  GenericVector<char> checkpoint;
390  if (!checkpoint_writer_->Run(FULL, this, &checkpoint) ||
391  !(*file_writer_)(checkpoint, checkpoint_name_.c_str())) {
392  *log_msg += " failed to write checkpoint.";
393  } else {
394  *log_msg += " wrote checkpoint.";
395  }
396  }
397  *log_msg += "\n";
398  return result;
399 }
bool empty() const
Definition: genericvector.h:91
const double kMinDivergenceRate
Definition: lstmtrainer.cpp:46
void StartSubtrainer(STRING *log_msg)
bool TransitionTrainingStage(float error_threshold)
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
const int kMinStartedErrorRate
Definition: lstmtrainer.cpp:61
CheckPointReader checkpoint_reader_
Definition: lstmtrainer.h:424
const char * c_str() const
Definition: strngs.cpp:205
STRING UpdateErrorGraph(int iteration, double error_rate, const GenericVector< char > &model_data, TestCallback tester)
virtual R Run(A1, A2)=0
const double kSubTrainerMarginFraction
Definition: lstmtrainer.cpp:51
SubTrainerResult UpdateSubtrainer(STRING *log_msg)
double CharError() const
Definition: lstmtrainer.h:139
int32_t length() const
Definition: strngs.cpp:189
const double kStageTransitionThreshold
Definition: lstmtrainer.cpp:63
int learning_iteration() const
Definition: lstmtrainer.h:149
void SaveRecognitionDump(GenericVector< char > *data) const
CheckPointWriter checkpoint_writer_
Definition: lstmtrainer.h:425
void add_str_int(const char *str, int number)
Definition: strngs.cpp:377
const int kMinStallIterations
Definition: lstmtrainer.cpp:48
void PrepareLogMsg(STRING *log_msg) const
float error_rate_of_last_saved_best_
Definition: lstmtrainer.h:452
Definition: strngs.h:45
void LogIterations(const char *intro_str, STRING *log_msg) const
STRING DumpFilename() const
const double kBestCheckpointFraction
Definition: lstmtrainer.cpp:69
void ReduceLearningRates(LSTMTrainer *samples_trainer, STRING *log_msg)
int CurrentTrainingStage() const
Definition: lstmtrainer.h:211
GenericVector< char > best_trainer_
Definition: lstmtrainer.h:447
virtual R Run(A1, A2, A3)=0
void add_str_double(const char *str, double number)
Definition: strngs.cpp:387

◆ MaintainCheckpointsSpecific()

bool tesseract::LSTMTrainer::MaintainCheckpointsSpecific ( int  iteration,
const GenericVector< char > *  train_model,
const GenericVector< char > *  rec_model,
TestCallback  tester,
STRING log_msg 
)

◆ MapRecoder()

std::vector< int > tesseract::LSTMTrainer::MapRecoder ( const UNICHARSET old_chset,
const UnicharCompress old_recoder 
) const

Definition at line 961 of file lstmtrainer.cpp.

962  {
963  int num_new_codes = recoder_.code_range();
964  int num_new_unichars = GetUnicharset().size();
965  std::vector<int> code_map(num_new_codes, -1);
966  for (int c = 0; c < num_new_codes; ++c) {
967  int old_code = -1;
968  // Find all new unichar_ids that recode to something that includes c.
969  // The <= is to include the null char, which may be beyond the unicharset.
970  for (int uid = 0; uid <= num_new_unichars; ++uid) {
971  RecodedCharID codes;
972  int length = recoder_.EncodeUnichar(uid, &codes);
973  int code_index = 0;
974  while (code_index < length && codes(code_index) != c) ++code_index;
975  if (code_index == length) continue;
976  // The old unicharset must have the same unichar.
977  int old_uid =
978  uid < num_new_unichars
979  ? old_chset.unichar_to_id(GetUnicharset().id_to_unichar(uid))
980  : old_chset.size() - 1;
981  if (old_uid == INVALID_UNICHAR_ID) continue;
982  // The encoding of old_uid at the same code_index is the old code.
983  RecodedCharID old_codes;
984  if (code_index < old_recoder.EncodeUnichar(old_uid, &old_codes)) {
985  old_code = old_codes(code_index);
986  break;
987  }
988  }
989  code_map[c] = old_code;
990  }
991  return code_map;
992 }
int size() const
Definition: unicharset.h:341
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
const UNICHARSET & GetUnicharset() const
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:210

◆ mutable_training_data()

DocumentCache* tesseract::LSTMTrainer::mutable_training_data ( )
inline

Definition at line 168 of file lstmtrainer.h.

168 { return &training_data_; }
DocumentCache training_data_
Definition: lstmtrainer.h:414

◆ NewSingleError()

double tesseract::LSTMTrainer::NewSingleError ( ErrorTypes  type) const
inline

Definition at line 154 of file lstmtrainer.h.

154  {
156  }
static const int kRollingBufferSize_
Definition: lstmtrainer.h:478
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479

◆ PrepareForBackward()

Trainability tesseract::LSTMTrainer::PrepareForBackward ( const ImageData trainingdata,
NetworkIO fwd_outputs,
NetworkIO targets 
)

Definition at line 800 of file lstmtrainer.cpp.

802  {
803  if (trainingdata == nullptr) {
804  tprintf("Null trainingdata.\n");
805  return UNENCODABLE;
806  }
807  // Ensure repeatability of random elements even across checkpoints.
808  bool debug = debug_interval_ > 0 &&
810  GenericVector<int> truth_labels;
811  if (!EncodeString(trainingdata->transcription(), &truth_labels)) {
812  tprintf("Can't encode transcription: '%s' in language '%s'\n",
813  trainingdata->transcription().string(),
814  trainingdata->language().string());
815  return UNENCODABLE;
816  }
817  bool upside_down = false;
818  if (randomly_rotate_) {
819  // This ensures consistent training results.
820  SetRandomSeed();
821  upside_down = randomizer_.SignedRand(1.0) > 0.0;
822  if (upside_down) {
823  // Modify the truth labels to match the rotation:
824  // Apart from space and null, increment the label. This is changes the
825  // script-id to the same script-id but upside-down.
826  // The labels need to be reversed in order, as the first is now the last.
827  for (int c = 0; c < truth_labels.size(); ++c) {
828  if (truth_labels[c] != UNICHAR_SPACE && truth_labels[c] != null_char_)
829  ++truth_labels[c];
830  }
831  truth_labels.reverse();
832  }
833  }
834  int w = 0;
835  while (w < truth_labels.size() &&
836  (truth_labels[w] == UNICHAR_SPACE || truth_labels[w] == null_char_))
837  ++w;
838  if (w == truth_labels.size()) {
839  tprintf("Blank transcription: %s\n",
840  trainingdata->transcription().string());
841  return UNENCODABLE;
842  }
843  float image_scale;
844  NetworkIO inputs;
845  bool invert = trainingdata->boxes().empty();
846  if (!RecognizeLine(*trainingdata, invert, debug, invert, upside_down,
847  &image_scale, &inputs, fwd_outputs)) {
848  tprintf("Image not trainable\n");
849  return UNENCODABLE;
850  }
851  targets->Resize(*fwd_outputs, network_->NumOutputs());
852  LossType loss_type = OutputLossType();
853  if (loss_type == LT_SOFTMAX) {
854  if (!ComputeTextTargets(*fwd_outputs, truth_labels, targets)) {
855  tprintf("Compute simple targets failed!\n");
856  return UNENCODABLE;
857  }
858  } else if (loss_type == LT_CTC) {
859  if (!ComputeCTCTargets(truth_labels, fwd_outputs, targets)) {
860  tprintf("Compute CTC targets failed!\n");
861  return UNENCODABLE;
862  }
863  } else {
864  tprintf("Logistic outputs not implemented yet!\n");
865  return UNENCODABLE;
866  }
867  GenericVector<int> ocr_labels;
868  GenericVector<int> xcoords;
869  LabelsFromOutputs(*fwd_outputs, &ocr_labels, &xcoords);
870  // CTC does not produce correct target labels to begin with.
871  if (loss_type != LT_CTC) {
872  LabelsFromOutputs(*targets, &truth_labels, &xcoords);
873  }
874  if (!DebugLSTMTraining(inputs, *trainingdata, *fwd_outputs, truth_labels,
875  *targets)) {
876  tprintf("Input width was %d\n", inputs.Width());
877  return UNENCODABLE;
878  }
879  STRING ocr_text = DecodeLabels(ocr_labels);
880  STRING truth_text = DecodeLabels(truth_labels);
881  targets->SubtractAllFromFloat(*fwd_outputs);
882  if (debug_interval_ != 0) {
883  if (truth_text != ocr_text) {
884  tprintf("Iteration %d: BEST OCR TEXT : %s\n",
885  training_iteration(), ocr_text.string());
886  }
887  }
888  double char_error = ComputeCharError(truth_labels, ocr_labels);
889  double word_error = ComputeWordError(&truth_text, &ocr_text);
890  double delta_error = ComputeErrorRates(*targets, char_error, word_error);
891  if (debug_interval_ != 0) {
892  tprintf("File %s line %d %s:\n", trainingdata->imagefilename().string(),
893  trainingdata->page_number(), delta_error == 0.0 ? "(Perfect)" : "");
894  }
895  if (delta_error == 0.0) return PERFECT;
896  if (targets->AnySuspiciousTruth(kHighConfidence)) return HI_PRECISION_ERR;
897  return TRAINABLE;
898 }
LossType OutputLossType() const
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
bool DebugLSTMTraining(const NetworkIO &inputs, const ImageData &trainingdata, const NetworkIO &fwd_outputs, const GenericVector< int > &truth_labels, const NetworkIO &outputs)
double ComputeCharError(const GenericVector< int > &truth_str, const GenericVector< int > &ocr_str)
double ComputeErrorRates(const NetworkIO &deltas, double char_error, double word_error)
const char * string() const
Definition: strngs.cpp:194
bool ComputeTextTargets(const NetworkIO &outputs, const GenericVector< int > &truth_labels, NetworkIO *targets)
void RecognizeLine(const ImageData &image_data, bool invert, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words, int lstm_choice_mode=0)
STRING DecodeLabels(const GenericVector< int > &labels)
bool EncodeString(const STRING &str, GenericVector< int > *labels) const
Definition: lstmtrainer.h:246
bool ComputeCTCTargets(const GenericVector< int > &truth_labels, NetworkIO *outputs, NetworkIO *targets)
Definition: strngs.h:45
double SignedRand(double range)
Definition: helpers.h:55
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
double ComputeWordError(STRING *truth_str, STRING *ocr_str)
const double kHighConfidence
Definition: lstmtrainer.cpp:65
int size() const
Definition: genericvector.h:72
int NumOutputs() const
Definition: network.h:123

◆ PrepareLogMsg()

void tesseract::LSTMTrainer::PrepareLogMsg ( STRING log_msg) const

Definition at line 402 of file lstmtrainer.cpp.

402  {
403  LogIterations("At", log_msg);
404  log_msg->add_str_double(", Mean rms=", error_rates_[ET_RMS]);
405  log_msg->add_str_double("%, delta=", error_rates_[ET_DELTA]);
406  log_msg->add_str_double("%, char train=", error_rates_[ET_CHAR_ERROR]);
407  log_msg->add_str_double("%, word train=", error_rates_[ET_WORD_RECERR]);
408  log_msg->add_str_double("%, skip ratio=", error_rates_[ET_SKIP_RATIO]);
409  *log_msg += "%, ";
410 }
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
void LogIterations(const char *intro_str, STRING *log_msg) const
void add_str_double(const char *str, double number)
Definition: strngs.cpp:387

◆ ReadLocalTrainingDump()

bool tesseract::LSTMTrainer::ReadLocalTrainingDump ( const TessdataManager mgr,
const char *  data,
int  size 
)

Definition at line 913 of file lstmtrainer.cpp.

914  {
915  if (size == 0) {
916  tprintf("Warning: data size is 0 in LSTMTrainer::ReadLocalTrainingDump\n");
917  return false;
918  }
919  TFile fp;
920  fp.Open(data, size);
921  return DeSerialize(mgr, &fp);
922 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
bool DeSerialize(const TessdataManager *mgr, TFile *fp)

◆ ReadSizedTrainingDump()

bool tesseract::LSTMTrainer::ReadSizedTrainingDump ( const char *  data,
int  size,
LSTMTrainer trainer 
) const
inline

Definition at line 296 of file lstmtrainer.h.

297  {
298  return trainer->ReadLocalTrainingDump(&mgr_, data, size);
299  }
TessdataManager mgr_
Definition: lstmtrainer.h:483

◆ ReadTrainingDump()

bool tesseract::LSTMTrainer::ReadTrainingDump ( const GenericVector< char > &  data,
LSTMTrainer trainer 
) const
inline

Definition at line 291 of file lstmtrainer.h.

292  {
293  if (data.empty()) return false;
294  return ReadSizedTrainingDump(&data[0], data.size(), trainer);
295  }
bool empty() const
Definition: genericvector.h:91
bool ReadSizedTrainingDump(const char *data, int size, LSTMTrainer *trainer) const
Definition: lstmtrainer.h:296
int size() const
Definition: genericvector.h:72

◆ ReduceLayerLearningRates()

int tesseract::LSTMTrainer::ReduceLayerLearningRates ( double  factor,
int  num_samples,
LSTMTrainer samples_trainer 
)

Definition at line 611 of file lstmtrainer.cpp.

612  {
613  enum WhichWay {
614  LR_DOWN, // Learning rate will go down by factor.
615  LR_SAME, // Learning rate will stay the same.
616  LR_COUNT // Size of arrays.
617  };
619  int num_layers = layers.size();
620  GenericVector<int> num_weights;
621  num_weights.init_to_size(num_layers, 0);
622  GenericVector<double> bad_sums[LR_COUNT];
623  GenericVector<double> ok_sums[LR_COUNT];
624  for (int i = 0; i < LR_COUNT; ++i) {
625  bad_sums[i].init_to_size(num_layers, 0.0);
626  ok_sums[i].init_to_size(num_layers, 0.0);
627  }
628  double momentum_factor = 1.0 / (1.0 - momentum_);
629  GenericVector<char> orig_trainer;
630  samples_trainer->SaveTrainingDump(LIGHT, this, &orig_trainer);
631  for (int i = 0; i < num_layers; ++i) {
632  Network* layer = GetLayer(layers[i]);
633  num_weights[i] = layer->IsTraining() ? layer->num_weights() : 0;
634  }
635  int iteration = sample_iteration();
636  for (int s = 0; s < num_samples; ++s) {
637  // Which way will we modify the learning rate?
638  for (int ww = 0; ww < LR_COUNT; ++ww) {
639  // Transfer momentum to learning rate and adjust by the ww factor.
640  float ww_factor = momentum_factor;
641  if (ww == LR_DOWN) ww_factor *= factor;
642  // Make a copy of *this, so we can mess about without damaging anything.
643  LSTMTrainer copy_trainer;
644  samples_trainer->ReadTrainingDump(orig_trainer, &copy_trainer);
645  // Clear the updates, doing nothing else.
646  copy_trainer.network_->Update(0.0, 0.0, 0.0, 0);
647  // Adjust the learning rate in each layer.
648  for (int i = 0; i < num_layers; ++i) {
649  if (num_weights[i] == 0) continue;
650  copy_trainer.ScaleLayerLearningRate(layers[i], ww_factor);
651  }
652  copy_trainer.SetIteration(iteration);
653  // Train on the sample, but keep the update in updates_ instead of
654  // applying to the weights.
655  const ImageData* trainingdata =
656  copy_trainer.TrainOnLine(samples_trainer, true);
657  if (trainingdata == nullptr) continue;
658  // We'll now use this trainer again for each layer.
659  GenericVector<char> updated_trainer;
660  samples_trainer->SaveTrainingDump(LIGHT, &copy_trainer, &updated_trainer);
661  for (int i = 0; i < num_layers; ++i) {
662  if (num_weights[i] == 0) continue;
663  LSTMTrainer layer_trainer;
664  samples_trainer->ReadTrainingDump(updated_trainer, &layer_trainer);
665  Network* layer = layer_trainer.GetLayer(layers[i]);
666  // Update the weights in just the layer, using Adam if enabled.
667  layer->Update(0.0, momentum_, adam_beta_,
668  layer_trainer.training_iteration_ + 1);
669  // Zero the updates matrix again.
670  layer->Update(0.0, 0.0, 0.0, 0);
671  // Train again on the same sample, again holding back the updates.
672  layer_trainer.TrainOnLine(trainingdata, true);
673  // Count the sign changes in the updates in layer vs in copy_trainer.
674  float before_bad = bad_sums[ww][i];
675  float before_ok = ok_sums[ww][i];
676  layer->CountAlternators(*copy_trainer.GetLayer(layers[i]),
677  &ok_sums[ww][i], &bad_sums[ww][i]);
678  float bad_frac =
679  bad_sums[ww][i] + ok_sums[ww][i] - before_bad - before_ok;
680  if (bad_frac > 0.0f)
681  bad_frac = (bad_sums[ww][i] - before_bad) / bad_frac;
682  }
683  }
684  ++iteration;
685  }
686  int num_lowered = 0;
687  for (int i = 0; i < num_layers; ++i) {
688  if (num_weights[i] == 0) continue;
689  Network* layer = GetLayer(layers[i]);
690  float lr = GetLayerLearningRate(layers[i]);
691  double total_down = bad_sums[LR_DOWN][i] + ok_sums[LR_DOWN][i];
692  double total_same = bad_sums[LR_SAME][i] + ok_sums[LR_SAME][i];
693  double frac_down = bad_sums[LR_DOWN][i] / total_down;
694  double frac_same = bad_sums[LR_SAME][i] / total_same;
695  tprintf("Layer %d=%s: lr %g->%g%%, lr %g->%g%%", i, layer->name().string(),
696  lr * factor, 100.0 * frac_down, lr, 100.0 * frac_same);
697  if (frac_down < frac_same * kImprovementFraction) {
698  tprintf(" REDUCED\n");
699  ScaleLayerLearningRate(layers[i], factor);
700  ++num_lowered;
701  } else {
702  tprintf(" SAME\n");
703  }
704  }
705  if (num_lowered == 0) {
706  // Just lower everything to make sure.
707  for (int i = 0; i < num_layers; ++i) {
708  if (num_weights[i] > 0) {
709  ScaleLayerLearningRate(layers[i], factor);
710  ++num_lowered;
711  }
712  }
713  }
714  return num_lowered;
715 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
void init_to_size(int size, const T &t)
void ScaleLayerLearningRate(const STRING &id, double factor)
float GetLayerLearningRate(const STRING &id) const
Network * GetLayer(const STRING &id) const
const double kImprovementFraction
Definition: lstmtrainer.cpp:67
GenericVector< STRING > EnumerateLayers() const
int size() const
Definition: genericvector.h:72

◆ ReduceLearningRates()

void tesseract::LSTMTrainer::ReduceLearningRates ( LSTMTrainer samples_trainer,
STRING log_msg 
)

Definition at line 592 of file lstmtrainer.cpp.

593  {
595  int num_reduced = ReduceLayerLearningRates(
596  kLearningRateDecay, kNumAdjustmentIterations, samples_trainer);
597  log_msg->add_str_int("\nReduced learning rate on layers: ", num_reduced);
598  } else {
600  log_msg->add_str_double("\nReduced learning rate to :", learning_rate_);
601  }
602  *log_msg += "\n";
603 }
void ScaleLearningRate(double factor)
const int kNumAdjustmentIterations
Definition: lstmtrainer.cpp:55
int ReduceLayerLearningRates(double factor, int num_samples, LSTMTrainer *samples_trainer)
bool TestFlag(NetworkFlags flag) const
Definition: network.h:144
const double kLearningRateDecay
Definition: lstmtrainer.cpp:53
void add_str_int(const char *str, int number)
Definition: strngs.cpp:377
void add_str_double(const char *str, double number)
Definition: strngs.cpp:387

◆ RollErrorBuffers()

void tesseract::LSTMTrainer::RollErrorBuffers ( )
protected

Definition at line 1269 of file lstmtrainer.cpp.

1269  {
1271  if (NewSingleError(ET_DELTA) > 0.0)
1273  else
1276  if (debug_interval_ != 0) {
1277  tprintf("Mean rms=%g%%, delta=%g%%, train=%g%%(%g%%), skip ratio=%g%%\n",
1281  }
1282 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
double NewSingleError(ErrorTypes type) const
Definition: lstmtrainer.h:154

◆ SaveRecognitionDump()

void tesseract::LSTMTrainer::SaveRecognitionDump ( GenericVector< char > *  data) const

Definition at line 934 of file lstmtrainer.cpp.

934  {
935  TFile fp;
936  fp.OpenWrite(data);
940 }
bool Serialize(const TessdataManager *mgr, TFile *fp) const
TessdataManager mgr_
Definition: lstmtrainer.h:483
virtual void SetEnableTraining(TrainingState state)
Definition: network.cpp:110
#define ASSERT_HOST(x)
Definition: errcode.h:88

◆ SaveTraineddata()

bool tesseract::LSTMTrainer::SaveTraineddata ( const STRING filename)

Definition at line 925 of file lstmtrainer.cpp.

925  {
926  GenericVector<char> recognizer_data;
927  SaveRecognitionDump(&recognizer_data);
928  mgr_.OverwriteEntry(TESSDATA_LSTM, &recognizer_data[0],
929  recognizer_data.size());
930  return mgr_.SaveFile(filename, file_writer_);
931 }
bool SaveFile(const STRING &filename, FileWriter writer) const
void OverwriteEntry(TessdataType type, const char *data, int size)
void SaveRecognitionDump(GenericVector< char > *data) const
TessdataManager mgr_
Definition: lstmtrainer.h:483
int size() const
Definition: genericvector.h:72

◆ SaveTrainingDump()

bool tesseract::LSTMTrainer::SaveTrainingDump ( SerializeAmount  serialize_amount,
const LSTMTrainer trainer,
GenericVector< char > *  data 
) const

Definition at line 904 of file lstmtrainer.cpp.

906  {
907  TFile fp;
908  fp.OpenWrite(data);
909  return trainer->Serialize(serialize_amount, &mgr_, &fp);
910 }
TessdataManager mgr_
Definition: lstmtrainer.h:483

◆ Serialize()

bool tesseract::LSTMTrainer::Serialize ( SerializeAmount  serialize_amount,
const TessdataManager mgr,
TFile fp 
) const

Definition at line 433 of file lstmtrainer.cpp.

434  {
435  if (!LSTMRecognizer::Serialize(mgr, fp)) return false;
436  if (!fp->Serialize(&learning_iteration_)) return false;
437  if (!fp->Serialize(&prev_sample_iteration_)) return false;
438  if (!fp->Serialize(&perfect_delay_)) return false;
439  if (!fp->Serialize(&last_perfect_training_iteration_)) return false;
440  for (const auto & error_buffer : error_buffers_) {
441  if (!error_buffer.Serialize(fp)) return false;
442  }
443  if (!fp->Serialize(&error_rates_[0], countof(error_rates_))) return false;
444  if (!fp->Serialize(&training_stage_)) return false;
445  uint8_t amount = serialize_amount;
446  if (!fp->Serialize(&amount)) return false;
447  if (serialize_amount == LIGHT) return true; // We are done.
448  if (!fp->Serialize(&best_error_rate_)) return false;
449  if (!fp->Serialize(&best_error_rates_[0], countof(best_error_rates_))) return false;
450  if (!fp->Serialize(&best_iteration_)) return false;
451  if (!fp->Serialize(&worst_error_rate_)) return false;
452  if (!fp->Serialize(&worst_error_rates_[0], countof(worst_error_rates_))) return false;
453  if (!fp->Serialize(&worst_iteration_)) return false;
454  if (!fp->Serialize(&stall_iteration_)) return false;
455  if (!best_model_data_.Serialize(fp)) return false;
456  if (!worst_model_data_.Serialize(fp)) return false;
457  if (serialize_amount != NO_BEST_TRAINER && !best_trainer_.Serialize(fp))
458  return false;
459  GenericVector<char> sub_data;
460  if (sub_trainer_ != nullptr && !SaveTrainingDump(LIGHT, sub_trainer_, &sub_data))
461  return false;
462  if (!sub_data.Serialize(fp)) return false;
463  if (!best_error_history_.Serialize(fp)) return false;
464  if (!best_error_iterations_.Serialize(fp)) return false;
465  return fp->Serialize(&improvement_steps_);
466 }
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
GenericVector< int > best_error_iterations_
Definition: lstmtrainer.h:458
GenericVector< char > worst_model_data_
Definition: lstmtrainer.h:445
double best_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:432
GenericVector< double > best_error_history_
Definition: lstmtrainer.h:457
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
constexpr size_t countof(T const (&)[N]) noexcept
Definition: serialis.h:43
double worst_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:438
bool Serialize(const TessdataManager *mgr, TFile *fp) const
GenericVector< char > best_model_data_
Definition: lstmtrainer.h:444
GenericVector< char > best_trainer_
Definition: lstmtrainer.h:447
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const
bool Serialize(FILE *fp) const
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479

◆ set_perfect_delay()

void tesseract::LSTMTrainer::set_perfect_delay ( int  delay)
inline

Definition at line 151 of file lstmtrainer.h.

151 { perfect_delay_ = delay; }

◆ SetNullChar()

void tesseract::LSTMTrainer::SetNullChar ( )
protected

Definition at line 1009 of file lstmtrainer.cpp.

1009  {
1011  : GetUnicharset().size();
1012  RecodedCharID code;
1014  null_char_ = code(0);
1015 }
int size() const
Definition: unicharset.h:341
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
const UNICHARSET & GetUnicharset() const
bool has_special_codes() const
Definition: unicharset.h:722

◆ SetupCheckpointInfo()

void tesseract::LSTMTrainer::SetupCheckpointInfo ( )

◆ StartSubtrainer()

void tesseract::LSTMTrainer::StartSubtrainer ( STRING log_msg)

Definition at line 519 of file lstmtrainer.cpp.

519  {
520  delete sub_trainer_;
521  sub_trainer_ = new LSTMTrainer();
523  *log_msg += " Failed to revert to previous best for trial!";
524  delete sub_trainer_;
525  sub_trainer_ = nullptr;
526  } else {
527  log_msg->add_str_int(" Trial sub_trainer_ from iteration ",
529  // Reduce learning rate so it doesn't diverge this time.
530  sub_trainer_->ReduceLearningRates(this, log_msg);
531  // If it fails again, we will wait twice as long before reverting again.
532  int stall_offset =
534  stall_iteration_ = learning_iteration() + 2 * stall_offset;
536  // Re-save the best trainer with the new learning rates and stall iteration.
538  }
539 }
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
CheckPointReader checkpoint_reader_
Definition: lstmtrainer.h:424
virtual R Run(A1, A2)=0
int learning_iteration() const
Definition: lstmtrainer.h:149
CheckPointWriter checkpoint_writer_
Definition: lstmtrainer.h:425
void add_str_int(const char *str, int number)
Definition: strngs.cpp:377
void ReduceLearningRates(LSTMTrainer *samples_trainer, STRING *log_msg)
GenericVector< char > best_trainer_
Definition: lstmtrainer.h:447
virtual R Run(A1, A2, A3)=0

◆ training_data()

const DocumentCache& tesseract::LSTMTrainer::training_data ( ) const
inline

Definition at line 165 of file lstmtrainer.h.

165  {
166  return training_data_;
167  }
DocumentCache training_data_
Definition: lstmtrainer.h:414

◆ TrainOnLine() [1/2]

const ImageData* tesseract::LSTMTrainer::TrainOnLine ( LSTMTrainer samples_trainer,
bool  batch 
)
inline

Definition at line 259 of file lstmtrainer.h.

259  {
260  int sample_index = sample_iteration();
261  const ImageData* image =
262  samples_trainer->training_data_.GetPageBySerial(sample_index);
263  if (image != nullptr) {
264  Trainability trainable = TrainOnLine(image, batch);
265  if (trainable == UNENCODABLE || trainable == NOT_BOXED) {
266  return nullptr; // Sample was unusable.
267  }
268  } else {
270  }
271  return image;
272  }
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
Definition: lstmtrainer.h:259

◆ TrainOnLine() [2/2]

Trainability tesseract::LSTMTrainer::TrainOnLine ( const ImageData trainingdata,
bool  batch 
)

Definition at line 767 of file lstmtrainer.cpp.

768  {
769  NetworkIO fwd_outputs, targets;
770  Trainability trainable =
771  PrepareForBackward(trainingdata, &fwd_outputs, &targets);
773  if (trainable == UNENCODABLE || trainable == NOT_BOXED) {
774  return trainable; // Sample was unusable.
775  }
776  bool debug = debug_interval_ > 0 &&
778  // Run backprop on the output.
779  NetworkIO bp_deltas;
780  if (network_->IsTraining() &&
781  (trainable != PERFECT ||
784  network_->Backward(debug, targets, &scratch_space_, &bp_deltas);
786  training_iteration_ + 1);
787  }
788 #ifndef GRAPHICS_DISABLED
789  if (debug_interval_ == 1 && debug_win_ != nullptr) {
791  }
792 #endif // GRAPHICS_DISABLED
793  // Roll the memory of past means.
795  return trainable;
796 }
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
SVEvent * AwaitEvent(SVEventType type)
Definition: scrollview.cpp:443
virtual void Update(float learning_rate, float momentum, float adam_beta, int num_samples)
Definition: network.h:230
NetworkScratch scratch_space_
bool IsTraining() const
Definition: network.h:115
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)=0

◆ TransitionTrainingStage()

bool tesseract::LSTMTrainer::TransitionTrainingStage ( float  error_threshold)

Definition at line 423 of file lstmtrainer.cpp.

423  {
424  if (best_error_rate_ < error_threshold &&
426  ++training_stage_;
427  return true;
428  }
429  return false;
430 }

◆ TryLoadingCheckpoint()

bool tesseract::LSTMTrainer::TryLoadingCheckpoint ( const char *  filename,
const char *  old_traineddata 
)

Definition at line 129 of file lstmtrainer.cpp.

130  {
131  GenericVector<char> data;
132  if (!(*file_reader_)(filename, &data)) return false;
133  tprintf("Loaded file %s, unpacking...\n", filename);
134  if (!checkpoint_reader_->Run(data, this)) return false;
135  if (IsIntMode()) {
136  tprintf("Error, %s is an integer (fast) model, cannot continue training\n", filename);
137  return false;
138  }
139  StaticShape shape = network_->OutputShape(network_->InputShape());
140  if (((old_traineddata == nullptr || *old_traineddata == '\0') &&
142  filename == old_traineddata) {
143  return true; // Normal checkpoint load complete.
144  }
145  tprintf("Code range changed from %d to %d!\n", network_->NumOutputs(),
146  recoder_.code_range());
147  if (old_traineddata == nullptr || *old_traineddata == '\0') {
148  tprintf("Must supply the old traineddata for code conversion!\n");
149  return false;
150  }
151  TessdataManager old_mgr;
152  ASSERT_HOST(old_mgr.Init(old_traineddata));
153  TFile fp;
154  if (!old_mgr.GetComponent(TESSDATA_LSTM_UNICHARSET, &fp)) return false;
155  UNICHARSET old_chset;
156  if (!old_chset.load_from_file(&fp, false)) return false;
157  if (!old_mgr.GetComponent(TESSDATA_LSTM_RECODER, &fp)) return false;
158  UnicharCompress old_recoder;
159  if (!old_recoder.DeSerialize(&fp)) return false;
160  std::vector<int> code_map = MapRecoder(old_chset, old_recoder);
161  // Set the null_char_ to the new value.
162  int old_null_char = null_char_;
163  SetNullChar();
164  // Map the softmax(s) in the network.
165  network_->RemapOutputs(old_recoder.code_range(), code_map);
166  tprintf("Previous null char=%d mapped to %d\n", old_null_char, null_char_);
167  return true;
168 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
CheckPointReader checkpoint_reader_
Definition: lstmtrainer.h:424
virtual R Run(A1, A2)=0
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
virtual StaticShape InputShape() const
Definition: network.h:127
int NumOutputs() const
Definition: network.h:123
#define ASSERT_HOST(x)
Definition: errcode.h:88
virtual int RemapOutputs(int old_no, const std::vector< int > &code_map)
Definition: network.h:186
bool load_from_file(const char *const filename, bool skip_fragments)
Definition: unicharset.h:388

◆ UpdateErrorBuffer()

void tesseract::LSTMTrainer::UpdateErrorBuffer ( double  new_error,
ErrorTypes  type 
)
protected

Definition at line 1256 of file lstmtrainer.cpp.

1256  {
1258  error_buffers_[type][index] = new_error;
1259  // Compute the mean error.
1260  int mean_count = std::min(training_iteration_ + 1, error_buffers_[type].size());
1261  double buffer_sum = 0.0;
1262  for (int i = 0; i < mean_count; ++i) buffer_sum += error_buffers_[type][i];
1263  double mean = buffer_sum / mean_count;
1264  // Trim precision to 1/1000 of 1%.
1265  error_rates_[type] = IntCastRounded(100000.0 * mean) / 1000.0;
1266 }
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
static const int kRollingBufferSize_
Definition: lstmtrainer.h:478
int IntCastRounded(double x)
Definition: helpers.h:175
GenericVector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:479

◆ UpdateErrorGraph()

STRING tesseract::LSTMTrainer::UpdateErrorGraph ( int  iteration,
double  error_rate,
const GenericVector< char > &  model_data,
TestCallback  tester 
)
protected

Definition at line 1288 of file lstmtrainer.cpp.

1290  {
1291  if (error_rate > best_error_rate_
1292  && iteration < best_iteration_ + kErrorGraphInterval) {
1293  // Too soon to record a new point.
1294  if (tester != nullptr && !worst_model_data_.empty()) {
1297  return tester->Run(worst_iteration_, nullptr, mgr_, CurrentTrainingStage());
1298  } else {
1299  return "";
1300  }
1301  }
1302  STRING result;
1303  // NOTE: there are 2 asymmetries here:
1304  // 1. We are computing the global minimum, but the local maximum in between.
1305  // 2. If the tester returns an empty string, indicating that it is busy,
1306  // call it repeatedly on new local maxima to test the previous min, but
1307  // not the other way around, as there is little point testing the maxima
1308  // between very frequent minima.
1309  if (error_rate < best_error_rate_) {
1310  // This is a new (global) minimum.
1311  if (tester != nullptr && !worst_model_data_.empty()) {
1314  result = tester->Run(worst_iteration_, worst_error_rates_, mgr_,
1317  best_model_data_ = model_data;
1318  }
1319  best_error_rate_ = error_rate;
1320  memcpy(best_error_rates_, error_rates_, sizeof(error_rates_));
1321  best_iteration_ = iteration;
1322  best_error_history_.push_back(error_rate);
1323  best_error_iterations_.push_back(iteration);
1324  // Compute 2% decay time.
1325  double two_percent_more = error_rate + 2.0;
1326  int i;
1327  for (i = best_error_history_.size() - 1;
1328  i >= 0 && best_error_history_[i] < two_percent_more; --i) {
1329  }
1330  int old_iteration = i >= 0 ? best_error_iterations_[i] : 0;
1331  improvement_steps_ = iteration - old_iteration;
1332  tprintf("2 Percent improvement time=%d, best error was %g @ %d\n",
1333  improvement_steps_, i >= 0 ? best_error_history_[i] : 100.0,
1334  old_iteration);
1335  } else if (error_rate > best_error_rate_) {
1336  // This is a new (local) maximum.
1337  if (tester != nullptr) {
1338  if (!best_model_data_.empty()) {
1341  result = tester->Run(best_iteration_, best_error_rates_, mgr_,
1343  } else if (!worst_model_data_.empty()) {
1344  // Allow for multiple data points with "worst" error rate.
1347  result = tester->Run(worst_iteration_, worst_error_rates_, mgr_,
1349  }
1350  if (result.length() > 0)
1352  worst_model_data_ = model_data;
1353  }
1354  }
1355  worst_error_rate_ = error_rate;
1356  memcpy(worst_error_rates_, error_rates_, sizeof(error_rates_));
1357  worst_iteration_ = iteration;
1358  return result;
1359 }
bool empty() const
Definition: genericvector.h:91
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
const int kErrorGraphInterval
Definition: lstmtrainer.cpp:57
GenericVector< int > best_error_iterations_
Definition: lstmtrainer.h:458
void OverwriteEntry(TessdataType type, const char *data, int size)
GenericVector< char > worst_model_data_
Definition: lstmtrainer.h:445
double best_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:432
GenericVector< double > best_error_history_
Definition: lstmtrainer.h:457
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:481
void truncate(int size)
int32_t length() const
Definition: strngs.cpp:189
double worst_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:438
TessdataManager mgr_
Definition: lstmtrainer.h:483
GenericVector< char > best_model_data_
Definition: lstmtrainer.h:444
Definition: strngs.h:45
int CurrentTrainingStage() const
Definition: lstmtrainer.h:211
int push_back(T object)
int size() const
Definition: genericvector.h:72

◆ UpdateSubtrainer()

SubTrainerResult tesseract::LSTMTrainer::UpdateSubtrainer ( STRING log_msg)

Definition at line 549 of file lstmtrainer.cpp.

549  {
550  double training_error = CharError();
551  double sub_error = sub_trainer_->CharError();
552  double sub_margin = (training_error - sub_error) / sub_error;
553  if (sub_margin >= kSubTrainerMarginFraction) {
554  log_msg->add_str_double(" sub_trainer=", sub_error);
555  log_msg->add_str_double(" margin=", 100.0 * sub_margin);
556  *log_msg += "\n";
557  // Catch up to current iteration.
558  int end_iteration = training_iteration();
559  while (sub_trainer_->training_iteration() < end_iteration &&
560  sub_margin >= kSubTrainerMarginFraction) {
561  int target_iteration =
563  while (sub_trainer_->training_iteration() < target_iteration) {
564  sub_trainer_->TrainOnLine(this, false);
565  }
566  STRING batch_log = "Sub:";
567  sub_trainer_->PrepareLogMsg(&batch_log);
568  batch_log += "\n";
569  tprintf("UpdateSubtrainer:%s", batch_log.string());
570  *log_msg += batch_log;
571  sub_error = sub_trainer_->CharError();
572  sub_margin = (training_error - sub_error) / sub_error;
573  }
574  if (sub_error < best_error_rate_ &&
575  sub_margin >= kSubTrainerMarginFraction) {
576  // The sub_trainer_ has won the race to a new best. Switch to it.
577  GenericVector<char> updated_trainer;
578  SaveTrainingDump(LIGHT, sub_trainer_, &updated_trainer);
579  ReadTrainingDump(updated_trainer, this);
580  log_msg->add_str_int(" Sub trainer wins at iteration ",
582  *log_msg += "\n";
583  return STR_REPLACED;
584  }
585  return STR_UPDATED;
586  }
587  return STR_NONE;
588 }
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:35
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
Definition: lstmtrainer.h:291
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
Definition: lstmtrainer.h:259
const int kNumPagesPerBatch
Definition: lstmtrainer.cpp:59
LSTMTrainer * sub_trainer_
Definition: lstmtrainer.h:450
const char * string() const
Definition: strngs.cpp:194
const double kSubTrainerMarginFraction
Definition: lstmtrainer.cpp:51
double CharError() const
Definition: lstmtrainer.h:139
void PrepareLogMsg(STRING *log_msg) const
Definition: strngs.h:45
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const
void add_str_double(const char *str, double number)
Definition: strngs.cpp:387

Member Data Documentation

◆ align_win_

ScrollView* tesseract::LSTMTrainer::align_win_
protected

Definition at line 397 of file lstmtrainer.h.

◆ best_error_history_

GenericVector<double> tesseract::LSTMTrainer::best_error_history_
protected

Definition at line 457 of file lstmtrainer.h.

◆ best_error_iterations_

GenericVector<int> tesseract::LSTMTrainer::best_error_iterations_
protected

Definition at line 458 of file lstmtrainer.h.

◆ best_error_rate_

double tesseract::LSTMTrainer::best_error_rate_
protected

Definition at line 430 of file lstmtrainer.h.

◆ best_error_rates_

double tesseract::LSTMTrainer::best_error_rates_[ET_COUNT]
protected

Definition at line 432 of file lstmtrainer.h.

◆ best_iteration_

int tesseract::LSTMTrainer::best_iteration_
protected

Definition at line 434 of file lstmtrainer.h.

◆ best_model_data_

GenericVector<char> tesseract::LSTMTrainer::best_model_data_
protected

Definition at line 444 of file lstmtrainer.h.

◆ best_model_name_

STRING tesseract::LSTMTrainer::best_model_name_
protected

Definition at line 416 of file lstmtrainer.h.

◆ best_trainer_

GenericVector<char> tesseract::LSTMTrainer::best_trainer_
protected

Definition at line 447 of file lstmtrainer.h.

◆ checkpoint_iteration_

int tesseract::LSTMTrainer::checkpoint_iteration_
protected

Definition at line 407 of file lstmtrainer.h.

◆ checkpoint_name_

STRING tesseract::LSTMTrainer::checkpoint_name_
protected

Definition at line 411 of file lstmtrainer.h.

◆ checkpoint_reader_

CheckPointReader tesseract::LSTMTrainer::checkpoint_reader_
protected

Definition at line 424 of file lstmtrainer.h.

◆ checkpoint_writer_

CheckPointWriter tesseract::LSTMTrainer::checkpoint_writer_
protected

Definition at line 425 of file lstmtrainer.h.

◆ ctc_win_

ScrollView* tesseract::LSTMTrainer::ctc_win_
protected

Definition at line 401 of file lstmtrainer.h.

◆ debug_interval_

int tesseract::LSTMTrainer::debug_interval_
protected

Definition at line 405 of file lstmtrainer.h.

◆ error_buffers_

GenericVector<double> tesseract::LSTMTrainer::error_buffers_[ET_COUNT]
protected

Definition at line 479 of file lstmtrainer.h.

◆ error_rate_of_last_saved_best_

float tesseract::LSTMTrainer::error_rate_of_last_saved_best_
protected

Definition at line 452 of file lstmtrainer.h.

◆ error_rates_

double tesseract::LSTMTrainer::error_rates_[ET_COUNT]
protected

Definition at line 481 of file lstmtrainer.h.

◆ file_reader_

FileReader tesseract::LSTMTrainer::file_reader_
protected

Definition at line 420 of file lstmtrainer.h.

◆ file_writer_

FileWriter tesseract::LSTMTrainer::file_writer_
protected

Definition at line 421 of file lstmtrainer.h.

◆ improvement_steps_

int32_t tesseract::LSTMTrainer::improvement_steps_
protected

Definition at line 460 of file lstmtrainer.h.

◆ kRollingBufferSize_

const int tesseract::LSTMTrainer::kRollingBufferSize_ = 1000
staticprotected

Definition at line 478 of file lstmtrainer.h.

◆ last_perfect_training_iteration_

int tesseract::LSTMTrainer::last_perfect_training_iteration_
protected

Definition at line 475 of file lstmtrainer.h.

◆ learning_iteration_

int tesseract::LSTMTrainer::learning_iteration_
protected

Definition at line 464 of file lstmtrainer.h.

◆ mgr_

TessdataManager tesseract::LSTMTrainer::mgr_
protected

Definition at line 483 of file lstmtrainer.h.

◆ model_base_

STRING tesseract::LSTMTrainer::model_base_
protected

Definition at line 409 of file lstmtrainer.h.

◆ num_training_stages_

int tesseract::LSTMTrainer::num_training_stages_
protected

Definition at line 418 of file lstmtrainer.h.

◆ perfect_delay_

int tesseract::LSTMTrainer::perfect_delay_
protected

Definition at line 472 of file lstmtrainer.h.

◆ prev_sample_iteration_

int tesseract::LSTMTrainer::prev_sample_iteration_
protected

Definition at line 466 of file lstmtrainer.h.

◆ randomly_rotate_

bool tesseract::LSTMTrainer::randomly_rotate_
protected

Definition at line 413 of file lstmtrainer.h.

◆ recon_win_

ScrollView* tesseract::LSTMTrainer::recon_win_
protected

Definition at line 403 of file lstmtrainer.h.

◆ stall_iteration_

int tesseract::LSTMTrainer::stall_iteration_
protected

Definition at line 442 of file lstmtrainer.h.

◆ sub_trainer_

LSTMTrainer* tesseract::LSTMTrainer::sub_trainer_
protected

Definition at line 450 of file lstmtrainer.h.

◆ target_win_

ScrollView* tesseract::LSTMTrainer::target_win_
protected

Definition at line 399 of file lstmtrainer.h.

◆ training_data_

DocumentCache tesseract::LSTMTrainer::training_data_
protected

Definition at line 414 of file lstmtrainer.h.

◆ training_stage_

int tesseract::LSTMTrainer::training_stage_
protected

Definition at line 454 of file lstmtrainer.h.

◆ worst_error_rate_

double tesseract::LSTMTrainer::worst_error_rate_
protected

Definition at line 436 of file lstmtrainer.h.

◆ worst_error_rates_

double tesseract::LSTMTrainer::worst_error_rates_[ET_COUNT]
protected

Definition at line 438 of file lstmtrainer.h.

◆ worst_iteration_

int tesseract::LSTMTrainer::worst_iteration_
protected

Definition at line 440 of file lstmtrainer.h.

◆ worst_model_data_

GenericVector<char> tesseract::LSTMTrainer::worst_model_data_
protected

Definition at line 445 of file lstmtrainer.h.


The documentation for this class was generated from the following files: