tesseract v5.3.3.20231005
tesseract::LSTMTrainer Class Reference

#include <lstmtrainer.h>

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

Public Member Functions

 LSTMTrainer ()
 
 LSTMTrainer (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)
 
bool InitCharSet (const std::string &traineddata_path)
 
void InitCharSet (const TessdataManager &mgr)
 
bool InitNetwork (const char *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 std::vector< 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, std::string &results)
 
void DebugNetwork ()
 
bool LoadAllTrainingData (const std::vector< std::string > &filenames, CachingStrategy cache_strategy, bool randomly_rotate)
 
bool MaintainCheckpoints (const TestCallback &tester, std::stringstream &log_msg)
 
bool MaintainCheckpointsSpecific (int iteration, const std::vector< char > *train_model, const std::vector< char > *rec_model, TestCallback tester, std::stringstream &log_msg)
 
void PrepareLogMsg (std::stringstream &log_msg) const
 
void LogIterations (const char *intro_str, std::stringstream &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 (std::stringstream &log_msg)
 
SubTrainerResult UpdateSubtrainer (std::stringstream &log_msg)
 
void ReduceLearningRates (LSTMTrainer *samples_trainer, std::stringstream &log_msg)
 
int ReduceLayerLearningRates (TFloat factor, int num_samples, LSTMTrainer *samples_trainer)
 
bool EncodeString (const std::string &str, std::vector< 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, std::vector< char > *data) const
 
bool ReadTrainingDump (const std::vector< 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 char *filename)
 
void SaveRecognitionDump (std::vector< char > *data) const
 
std::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 std::string &language_data_path_prefix)
 
 ~LSTMRecognizer ()
 
int NumOutputs () const
 
int training_iteration () const
 
int sample_iteration () const
 
float learning_rate () const
 
LossType OutputLossType () const
 
bool SimpleTextOutput () const
 
bool IsIntMode () const
 
bool IsRecoding () const
 
bool IsTensorFlow () const
 
std::vector< std::string > EnumerateLayers () const
 
NetworkGetLayer (const std::string &id) const
 
float GetLayerLearningRate (const std::string &id) const
 
const char * GetNetwork () const
 
float GetAdamBeta () const
 
float GetMomentum () const
 
void ScaleLearningRate (double factor)
 
void ScaleLayerLearningRate (const std::string &id, double factor)
 
void SetLearningRate (float learning_rate)
 
void SetLayerLearningRate (const std::string &id, float learning_rate)
 
void ConvertToInt ()
 
const UNICHARSETGetUnicharset () const
 
UNICHARSETGetUnicharset ()
 
const UnicharCompressGetRecoder () const
 
const DictGetDict () const
 
DictGetDict ()
 
void SetIteration (int iteration)
 
int NumInputs () const
 
int null_char () const
 
bool Load (const ParamsVectors *params, const std::string &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 std::string &lang, TessdataManager *mgr)
 
void RecognizeLine (const ImageData &image_data, float invert_threshold, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words, int lstm_choice_mode=0, int lstm_choice_amount=5)
 
void OutputStats (const NetworkIO &outputs, float *min_output, float *mean_output, float *sd)
 
bool RecognizeLine (const ImageData &image_data, float invert_threshold, bool debug, bool re_invert, bool upside_down, float *scale_factor, NetworkIO *inputs, NetworkIO *outputs)
 
std::string DecodeLabels (const std::vector< int > &labels)
 
void DisplayForward (const NetworkIO &inputs, const std::vector< int > &labels, const std::vector< int > &label_coords, const char *window_name, ScrollView **window)
 
void LabelsFromOutputs (const NetworkIO &outputs, std::vector< int > *labels, std::vector< int > *xcoords)
 

Static Public Member Functions

static bool EncodeString (const std::string &str, const UNICHARSET &unicharset, const UnicharCompress *recoder, bool simple_text, int null_char, std::vector< int > *labels)
 

Protected Member Functions

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

Protected Attributes

ScrollViewalign_win_
 
ScrollViewtarget_win_
 
ScrollViewctc_win_
 
ScrollViewrecon_win_
 
int debug_interval_
 
int checkpoint_iteration_
 
std::string model_base_
 
std::string checkpoint_name_
 
bool randomly_rotate_
 
DocumentCache training_data_
 
std::string best_model_name_
 
int num_training_stages_
 
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_
 
std::vector< char > best_model_data_
 
std::vector< char > worst_model_data_
 
std::vector< char > best_trainer_
 
std::unique_ptr< LSTMTrainersub_trainer_
 
float error_rate_of_last_saved_best_
 
int training_stage_
 
std::vector< double > best_error_history_
 
std::vector< int32_t > best_error_iterations_
 
int32_t improvement_steps_
 
int learning_iteration_
 
int prev_sample_iteration_
 
int perfect_delay_
 
int last_perfect_training_iteration_
 
std::vector< double > error_buffers_ [ET_COUNT]
 
double error_rates_ [ET_COUNT]
 
TessdataManager mgr_
 
- Protected Attributes inherited from tesseract::LSTMRecognizer
Networknetwork_
 
CCUtil ccutil_
 
UnicharCompress recoder_
 
std::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 84 of file lstmtrainer.h.

Constructor & Destructor Documentation

◆ LSTMTrainer() [1/2]

tesseract::LSTMTrainer::LSTMTrainer ( )

Definition at line 77 of file lstmtrainer.cpp.

78 : randomly_rotate_(false), training_data_(0), sub_trainer_(nullptr) {
81}
DocumentCache training_data_
Definition: lstmtrainer.h:426
std::unique_ptr< LSTMTrainer > sub_trainer_
Definition: lstmtrainer.h:455

◆ LSTMTrainer() [2/2]

tesseract::LSTMTrainer::LSTMTrainer ( const char *  model_base,
const char *  checkpoint_name,
int  debug_interval,
int64_t  max_memory 
)

Definition at line 83 of file lstmtrainer.cpp.

85 : randomly_rotate_(false),
86 training_data_(max_memory),
87 sub_trainer_(nullptr) {
89 debug_interval_ = debug_interval;
90 model_base_ = model_base;
91 checkpoint_name_ = checkpoint_name;
92}
std::string model_base_
Definition: lstmtrainer.h:421
std::string checkpoint_name_
Definition: lstmtrainer.h:423

◆ ~LSTMTrainer()

tesseract::LSTMTrainer::~LSTMTrainer ( )
virtual

Definition at line 94 of file lstmtrainer.cpp.

94 {
95#ifndef GRAPHICS_DISABLED
96 delete align_win_;
97 delete target_win_;
98 delete ctc_win_;
99 delete recon_win_;
100#endif
101}
ScrollView * target_win_
Definition: lstmtrainer.h:410
ScrollView * recon_win_
Definition: lstmtrainer.h:414
ScrollView * ctc_win_
Definition: lstmtrainer.h:412
ScrollView * align_win_
Definition: lstmtrainer.h:408

Member Function Documentation

◆ ActivationError()

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

Definition at line 130 of file lstmtrainer.h.

130 {
131 return error_rates_[ET_DELTA];
132 }
double error_rates_[ET_COUNT]
Definition: lstmtrainer.h:486

◆ best_error_rate()

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

Definition at line 139 of file lstmtrainer.h.

139 {
140 return best_error_rate_;
141 }

◆ best_iteration()

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

Definition at line 142 of file lstmtrainer.h.

142 {
143 return best_iteration_;
144 }

◆ best_trainer()

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

Definition at line 154 of file lstmtrainer.h.

154 {
155 return best_trainer_;
156 }
std::vector< char > best_trainer_
Definition: lstmtrainer.h:452

◆ CharError()

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

Definition at line 133 of file lstmtrainer.h.

133 {
135 }
@ ET_CHAR_ERROR
Definition: lstmtrainer.h:45

◆ ComputeCharError()

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

Definition at line 1323 of file lstmtrainer.cpp.

1324 {
1325 std::vector<int> label_counts(NumOutputs());
1326 unsigned truth_size = 0;
1327 for (auto ch : truth_str) {
1328 if (ch != null_char_) {
1329 ++label_counts[ch];
1330 ++truth_size;
1331 }
1332 }
1333 for (auto ch : ocr_str) {
1334 if (ch != null_char_) {
1335 --label_counts[ch];
1336 }
1337 }
1338 unsigned char_errors = 0;
1339 for (auto label_count : label_counts) {
1340 char_errors += abs(label_count);
1341 }
1342 // Limit BCER to interval [0,1] and avoid division by zero.
1343 if (truth_size <= char_errors) {
1344 return (char_errors == 0) ? 0.0 : 1.0;
1345 }
1346 return static_cast<double>(char_errors) / truth_size;
1347}

◆ ComputeCTCTargets()

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

Definition at line 1254 of file lstmtrainer.cpp.

1255 {
1256 // Bottom-clip outputs to a minimum probability.
1257 CTC::NormalizeProbs(outputs);
1258 return CTC::ComputeCTCTargets(truth_labels, null_char_,
1259 outputs->float_array(), targets);
1260}
static bool ComputeCTCTargets(const std::vector< int > &truth_labels, int null_char, const GENERIC_2D_ARRAY< float > &outputs, NetworkIO *targets)
Definition: ctc.cpp:53
static void NormalizeProbs(NetworkIO *probs)
Definition: ctc.h:36

◆ ComputeErrorRates()

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

Definition at line 1265 of file lstmtrainer.cpp.

1266 {
1268 // Delta error is the fraction of timesteps with >0.5 error in the top choice
1269 // score. If zero, then the top choice characters are guaranteed correct,
1270 // even when there is residue in the RMS error.
1271 double delta_error = ComputeWinnerError(deltas);
1272 UpdateErrorBuffer(delta_error, ET_DELTA);
1273 UpdateErrorBuffer(word_error, ET_WORD_RECERR);
1274 UpdateErrorBuffer(char_error, ET_CHAR_ERROR);
1275 // Skip ratio measures the difference between sample_iteration_ and
1276 // training_iteration_, which reflects the number of unusable samples,
1277 // usually due to unencodable truth text, or the text not fitting in the
1278 // space for the output.
1279 double skip_count = sample_iteration_ - prev_sample_iteration_;
1280 UpdateErrorBuffer(skip_count, ET_SKIP_RATIO);
1281 return delta_error;
1282}
@ ET_WORD_RECERR
Definition: lstmtrainer.h:44
@ ET_SKIP_RATIO
Definition: lstmtrainer.h:46
double ComputeRMSError(const NetworkIO &deltas)
double ComputeWinnerError(const NetworkIO &deltas)
void UpdateErrorBuffer(double new_error, ErrorTypes type)

◆ ComputeRMSError()

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

Definition at line 1285 of file lstmtrainer.cpp.

1285 {
1286 double total_error = 0.0;
1287 int width = deltas.Width();
1288 int num_classes = deltas.NumFeatures();
1289 for (int t = 0; t < width; ++t) {
1290 const float *class_errs = deltas.f(t);
1291 for (int c = 0; c < num_classes; ++c) {
1292 double error = class_errs[c];
1293 total_error += error * error;
1294 }
1295 }
1296 return sqrt(total_error / (width * num_classes));
1297}

◆ ComputeTextTargets()

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

Definition at line 1232 of file lstmtrainer.cpp.

1234 {
1235 if (truth_labels.size() > targets->Width()) {
1236 tprintf("Error: transcription %s too long to fit into target of width %d\n",
1237 DecodeLabels(truth_labels).c_str(), targets->Width());
1238 return false;
1239 }
1240 int i = 0;
1241 for (auto truth_label : truth_labels) {
1242 targets->SetActivations(i, truth_label, 1.0);
1243 ++i;
1244 }
1245 for (i = truth_labels.size(); i < targets->Width(); ++i) {
1246 targets->SetActivations(i, null_char_, 1.0);
1247 }
1248 return true;
1249}
void tprintf(const char *format,...)
Definition: tprintf.cpp:41
std::string DecodeLabels(const std::vector< int > &labels)

◆ ComputeWinnerError()

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

Definition at line 1304 of file lstmtrainer.cpp.

1304 {
1305 int num_errors = 0;
1306 int width = deltas.Width();
1307 int num_classes = deltas.NumFeatures();
1308 for (int t = 0; t < width; ++t) {
1309 const float *class_errs = deltas.f(t);
1310 for (int c = 0; c < num_classes; ++c) {
1311 float abs_delta = std::fabs(class_errs[c]);
1312 // TODO(rays) Filtering cases where the delta is very large to cut out
1313 // GT errors doesn't work. Find a better way or get better truth.
1314 if (0.5 <= abs_delta) {
1315 ++num_errors;
1316 }
1317 }
1318 }
1319 return static_cast<double>(num_errors) / width;
1320}

◆ ComputeWordError()

double tesseract::LSTMTrainer::ComputeWordError ( std::string *  truth_str,
std::string *  ocr_str 
)
protected

Definition at line 1351 of file lstmtrainer.cpp.

1352 {
1353 using StrMap = std::unordered_map<std::string, int, std::hash<std::string>>;
1354 std::vector<std::string> truth_words = split(*truth_str, ' ');
1355 if (truth_words.empty()) {
1356 return 0.0;
1357 }
1358 std::vector<std::string> ocr_words = split(*ocr_str, ' ');
1359 StrMap word_counts;
1360 for (const auto &truth_word : truth_words) {
1361 std::string truth_word_string(truth_word.c_str());
1362 auto it = word_counts.find(truth_word_string);
1363 if (it == word_counts.end()) {
1364 word_counts.insert(std::make_pair(truth_word_string, 1));
1365 } else {
1366 ++it->second;
1367 }
1368 }
1369 for (const auto &ocr_word : ocr_words) {
1370 std::string ocr_word_string(ocr_word.c_str());
1371 auto it = word_counts.find(ocr_word_string);
1372 if (it == word_counts.end()) {
1373 word_counts.insert(std::make_pair(ocr_word_string, -1));
1374 } else {
1375 --it->second;
1376 }
1377 }
1378 int word_recall_errs = 0;
1379 for (const auto &word_count : word_counts) {
1380 if (word_count.second > 0) {
1381 word_recall_errs += word_count.second;
1382 }
1383 }
1384 return static_cast<double>(word_recall_errs) / truth_words.size();
1385}
const std::vector< std::string > split(const std::string &s, char c)
Definition: helpers.h:43

◆ CurrentTrainingStage()

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

Definition at line 217 of file lstmtrainer.h.

217 {
218 return training_stage_;
219 }

◆ DebugLSTMTraining()

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

Definition at line 1154 of file lstmtrainer.cpp.

1158 {
1159 const std::string &truth_text = DecodeLabels(truth_labels);
1160 if (truth_text.c_str() == nullptr || truth_text.length() <= 0) {
1161 tprintf("Empty truth string at decode time!\n");
1162 return false;
1163 }
1164 if (debug_interval_ != 0) {
1165 // Get class labels, xcoords and string.
1166 std::vector<int> labels;
1167 std::vector<int> xcoords;
1168 LabelsFromOutputs(outputs, &labels, &xcoords);
1169 std::string text = DecodeLabels(labels);
1170 tprintf("Iteration %d: GROUND TRUTH : %s\n", training_iteration(),
1171 truth_text.c_str());
1172 if (truth_text != text) {
1173 tprintf("Iteration %d: ALIGNED TRUTH : %s\n", training_iteration(),
1174 text.c_str());
1175 }
1177 tprintf("TRAINING activation path for truth string %s\n",
1178 truth_text.c_str());
1179 DebugActivationPath(outputs, labels, xcoords);
1180#ifndef GRAPHICS_DISABLED
1181 DisplayForward(inputs, labels, xcoords, "LSTMTraining", &align_win_);
1182 if (OutputLossType() == LT_CTC) {
1183 DisplayTargets(fwd_outputs, "CTC Outputs", &ctc_win_);
1184 DisplayTargets(outputs, "CTC Targets", &target_win_);
1185 }
1186#endif
1187 }
1188 }
1189 return true;
1190}
void DebugActivationPath(const NetworkIO &outputs, const std::vector< int > &labels, const std::vector< int > &xcoords)
LossType OutputLossType() const
void LabelsFromOutputs(const NetworkIO &outputs, std::vector< int > *labels, std::vector< int > *xcoords)
void DisplayForward(const NetworkIO &inputs, const std::vector< int > &labels, const std::vector< int > &label_coords, const char *window_name, ScrollView **window)
void DisplayTargets(const NetworkIO &targets, const char *window_name, ScrollView **window)

◆ DebugNetwork()

void tesseract::LSTMTrainer::DebugNetwork ( )

Definition at line 289 of file lstmtrainer.cpp.

289 {
291}
virtual void DebugWeights()=0

◆ DeSerialize()

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

Definition at line 511 of file lstmtrainer.cpp.

511 {
512 if (!LSTMRecognizer::DeSerialize(mgr, fp)) {
513 return false;
514 }
515 if (!fp->DeSerialize(&learning_iteration_)) {
516 // Special case. If we successfully decoded the recognizer, but fail here
517 // then it means we were just given a recognizer, so issue a warning and
518 // allow it.
519 tprintf("Warning: LSTMTrainer deserialized an LSTMRecognizer!\n");
522 return true;
523 }
524 if (!fp->DeSerialize(&prev_sample_iteration_)) {
525 return false;
526 }
527 if (!fp->DeSerialize(&perfect_delay_)) {
528 return false;
529 }
530 if (!fp->DeSerialize(&last_perfect_training_iteration_)) {
531 return false;
532 }
533 for (auto &error_buffer : error_buffers_) {
534 if (!fp->DeSerialize(error_buffer)) {
535 return false;
536 }
537 }
538 if (!fp->DeSerialize(&error_rates_[0], countof(error_rates_))) {
539 return false;
540 }
541 if (!fp->DeSerialize(&training_stage_)) {
542 return false;
543 }
544 uint8_t amount;
545 if (!fp->DeSerialize(&amount)) {
546 return false;
547 }
548 if (amount == LIGHT) {
549 return true; // Don't read the rest.
550 }
551 if (!fp->DeSerialize(&best_error_rate_)) {
552 return false;
553 }
554 if (!fp->DeSerialize(&best_error_rates_[0], countof(best_error_rates_))) {
555 return false;
556 }
557 if (!fp->DeSerialize(&best_iteration_)) {
558 return false;
559 }
560 if (!fp->DeSerialize(&worst_error_rate_)) {
561 return false;
562 }
563 if (!fp->DeSerialize(&worst_error_rates_[0], countof(worst_error_rates_))) {
564 return false;
565 }
566 if (!fp->DeSerialize(&worst_iteration_)) {
567 return false;
568 }
569 if (!fp->DeSerialize(&stall_iteration_)) {
570 return false;
571 }
572 if (!fp->DeSerialize(best_model_data_)) {
573 return false;
574 }
575 if (!fp->DeSerialize(worst_model_data_)) {
576 return false;
577 }
578 if (amount != NO_BEST_TRAINER && !fp->DeSerialize(best_trainer_)) {
579 return false;
580 }
581 std::vector<char> sub_data;
582 if (!fp->DeSerialize(sub_data)) {
583 return false;
584 }
585 if (sub_data.empty()) {
586 sub_trainer_ = nullptr;
587 } else {
588 sub_trainer_ = std::make_unique<LSTMTrainer>();
589 if (!ReadTrainingDump(sub_data, *sub_trainer_)) {
590 return false;
591 }
592 }
593 if (!fp->DeSerialize(best_error_history_)) {
594 return false;
595 }
596 if (!fp->DeSerialize(best_error_iterations_)) {
597 return false;
598 }
599 return fp->DeSerialize(&improvement_steps_);
600}
constexpr size_t countof(T const (&)[N]) noexcept
Definition: serialis.h:34
@ TS_ENABLED
Definition: network.h:93
@ NO_BEST_TRAINER
Definition: lstmtrainer.h:62
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
virtual void SetEnableTraining(TrainingState state)
Definition: network.cpp:113
std::vector< int32_t > best_error_iterations_
Definition: lstmtrainer.h:463
std::vector< char > worst_model_data_
Definition: lstmtrainer.h:450
double worst_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:443
std::vector< char > best_model_data_
Definition: lstmtrainer.h:449
std::vector< double > error_buffers_[ET_COUNT]
Definition: lstmtrainer.h:484
bool ReadTrainingDump(const std::vector< char > &data, LSTMTrainer &trainer) const
Definition: lstmtrainer.h:300
std::vector< double > best_error_history_
Definition: lstmtrainer.h:462
double best_error_rates_[ET_COUNT]
Definition: lstmtrainer.h:437

◆ DisplayTargets()

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

Definition at line 1195 of file lstmtrainer.cpp.

1196 {
1197 int width = targets.Width();
1198 int num_features = targets.NumFeatures();
1199 Network::ClearWindow(true, window_name, width * kTargetXScale, kTargetYScale,
1200 window);
1201 for (int c = 0; c < num_features; ++c) {
1202 int color = c % (ScrollView::GREEN_YELLOW - 1) + 2;
1203 (*window)->Pen(static_cast<ScrollView::Color>(color));
1204 int start_t = -1;
1205 for (int t = 0; t < width; ++t) {
1206 double target = targets.f(t)[c];
1207 target *= kTargetYScale;
1208 if (target >= 1) {
1209 if (start_t < 0) {
1210 (*window)->SetCursor(t - 1, 0);
1211 start_t = t;
1212 }
1213 (*window)->DrawTo(t, target);
1214 } else if (start_t >= 0) {
1215 (*window)->DrawTo(t, 0);
1216 (*window)->DrawTo(start_t - 1, 0);
1217 start_t = -1;
1218 }
1219 }
1220 if (start_t >= 0) {
1221 (*window)->DrawTo(width, 0);
1222 (*window)->DrawTo(start_t - 1, 0);
1223 }
1224 }
1225 (*window)->Update();
1226}
const int kTargetYScale
Definition: lstmtrainer.cpp:74
const int kTargetXScale
Definition: lstmtrainer.cpp:73
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
Definition: network.cpp:350

◆ DumpFilename()

std::string tesseract::LSTMTrainer::DumpFilename ( ) const

Definition at line 1053 of file lstmtrainer.cpp.

1053 {
1054 std::stringstream filename;
1055 filename.imbue(std::locale::classic());
1056 filename << model_base_ << std::fixed << std::setprecision(3)
1057 << "_" << best_error_rate_
1058 << "_" << best_iteration_
1059 << "_" << training_iteration_
1060 << ".checkpoint";
1061 return filename.str();
1062}

◆ EmptyConstructor()

void tesseract::LSTMTrainer::EmptyConstructor ( )
protected

Definition at line 1137 of file lstmtrainer.cpp.

1137 {
1138#ifndef GRAPHICS_DISABLED
1139 align_win_ = nullptr;
1140 target_win_ = nullptr;
1141 ctc_win_ = nullptr;
1142 recon_win_ = nullptr;
1143#endif
1145 training_stage_ = 0;
1148}

◆ EncodeString() [1/2]

bool tesseract::LSTMTrainer::EncodeString ( const std::string &  str,
const UNICHARSET unicharset,
const UnicharCompress recoder,
bool  simple_text,
int  null_char,
std::vector< int > *  labels 
)
static

Definition at line 813 of file lstmtrainer.cpp.

816 {
817 if (str.c_str() == nullptr || str.length() <= 0) {
818 tprintf("Empty truth string!\n");
819 return false;
820 }
821 unsigned err_index;
822 std::vector<int> internal_labels;
823 labels->clear();
824 if (!simple_text) {
825 labels->push_back(null_char);
826 }
827 std::string cleaned = unicharset.CleanupString(str.c_str());
828 if (unicharset.encode_string(cleaned.c_str(), true, &internal_labels, nullptr,
829 &err_index)) {
830 bool success = true;
831 for (auto internal_label : internal_labels) {
832 if (recoder != nullptr) {
833 // Re-encode labels via recoder.
834 RecodedCharID code;
835 int len = recoder->EncodeUnichar(internal_label, &code);
836 if (len > 0) {
837 for (int j = 0; j < len; ++j) {
838 labels->push_back(code(j));
839 if (!simple_text) {
840 labels->push_back(null_char);
841 }
842 }
843 } else {
844 success = false;
845 err_index = 0;
846 break;
847 }
848 } else {
849 labels->push_back(internal_label);
850 if (!simple_text) {
851 labels->push_back(null_char);
852 }
853 }
854 }
855 if (success) {
856 return true;
857 }
858 }
859 tprintf("Encoding of string failed! Failure bytes:");
860 while (err_index < cleaned.size()) {
861 tprintf(" %x", cleaned[err_index++] & 0xff);
862 }
863 tprintf("\n");
864 return false;
865}

◆ EncodeString() [2/2]

bool tesseract::LSTMTrainer::EncodeString ( const std::string &  str,
std::vector< int > *  labels 
) const
inline

Definition at line 254 of file lstmtrainer.h.

254 {
255 return EncodeString(str, GetUnicharset(),
256 IsRecoding() ? &recoder_ : nullptr, SimpleTextOutput(),
257 null_char_, labels);
258 }
const UNICHARSET & GetUnicharset() const
bool EncodeString(const std::string &str, std::vector< int > *labels) const
Definition: lstmtrainer.h:254

◆ error_rates()

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

Definition at line 136 of file lstmtrainer.h.

136 {
137 return error_rates_;
138 }

◆ FillErrorBuffer()

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

Definition at line 1065 of file lstmtrainer.cpp.

1065 {
1066 for (int i = 0; i < kRollingBufferSize_; ++i) {
1067 error_buffers_[type][i] = new_error;
1068 }
1069 error_rates_[type] = 100.0 * new_error;
1070}
type
Definition: upload.py:458
static const int kRollingBufferSize_
Definition: lstmtrainer.h:483

◆ 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,
std::string &  results 
)

Definition at line 236 of file lstmtrainer.cpp.

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

◆ improvement_steps()

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

Definition at line 148 of file lstmtrainer.h.

148 {
149 return improvement_steps_;
150 }

◆ InitCharSet() [1/3]

void tesseract::LSTMTrainer::InitCharSet ( )
protected

Definition at line 1115 of file lstmtrainer.cpp.

1115 {
1118 // Initialize the unicharset and recoder.
1119 if (!LoadCharsets(&mgr_)) {
1121 "Must provide a traineddata containing lstm_unicharset and"
1122 " lstm_recoder!\n" != nullptr);
1123 }
1124 SetNullChar();
1125}
@ TF_COMPRESS_UNICHARSET
bool LoadCharsets(const TessdataManager *mgr)
TessdataManager mgr_
Definition: lstmtrainer.h:488

◆ InitCharSet() [2/3]

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

Definition at line 100 of file lstmtrainer.h.

100 {
101 bool success = mgr_.Init(traineddata_path.c_str());
102 if (success) {
103 InitCharSet();
104 }
105 return success;
106 }
bool Init(const char *data_file_name)

◆ InitCharSet() [3/3]

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

Definition at line 107 of file lstmtrainer.h.

107 {
108 mgr_ = mgr;
109 InitCharSet();
110 }

◆ InitIterations()

void tesseract::LSTMTrainer::InitIterations ( )

Definition at line 208 of file lstmtrainer.cpp.

208 {
213 best_error_rate_ = 100.0;
214 best_iteration_ = 0;
215 worst_error_rate_ = 0.0;
218 best_error_history_.clear();
221 perfect_delay_ = 0;
223 for (int i = 0; i < ET_COUNT; ++i) {
224 best_error_rates_[i] = 100.0;
225 worst_error_rates_[i] = 0.0;
226 error_buffers_[i].clear();
228 error_rates_[i] = 100.0;
229 }
231}
const int kMinStartedErrorRate
Definition: lstmtrainer.cpp:62
const int kMinStallIterations
Definition: lstmtrainer.cpp:49
float error_rate_of_last_saved_best_
Definition: lstmtrainer.h:457

◆ InitNetwork()

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

Definition at line 164 of file lstmtrainer.cpp.

167 {
168 mgr_.SetVersionString(mgr_.VersionString() + ":" + network_spec);
169 adam_beta_ = adam_beta;
171 momentum_ = momentum;
172 SetNullChar();
174 append_index, net_flags, weight_range,
175 &randomizer_, &network_)) {
176 return false;
177 }
178 network_str_ += network_spec;
179 tprintf("Built network:%s from request %s\n", network_->spec().c_str(),
180 network_spec);
181 tprintf(
182 "Training parameters:\n Debug interval = %d,"
183 " weights = %g, learning rate = %g, momentum=%g\n",
185 tprintf("null char=%d\n", null_char_);
186 return true;
187}
std::string VersionString() const
void SetVersionString(const std::string &v_str)
virtual std::string spec() const
Definition: network.h:143
static bool InitNetwork(int num_outputs, const char *network_spec, int append_index, int net_flags, float weight_range, TRand *randomizer, Network **network)

◆ InitTensorFlowNetwork()

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

◆ LastSingleError()

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

Definition at line 164 of file lstmtrainer.h.

164 {
165 return error_buffers_[type]
168 }

◆ learning_iteration()

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

Definition at line 145 of file lstmtrainer.h.

145 {
146 return learning_iteration_;
147 }

◆ LoadAllTrainingData()

bool tesseract::LSTMTrainer::LoadAllTrainingData ( const std::vector< std::string > &  filenames,
CachingStrategy  cache_strategy,
bool  randomly_rotate 
)

Definition at line 296 of file lstmtrainer.cpp.

298 {
299 randomly_rotate_ = randomly_rotate;
301 return training_data_.LoadDocuments(filenames, cache_strategy,
303}
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
TESS_API bool LoadDocuments(const std::vector< std::string > &filenames, CachingStrategy cache_strategy, FileReader reader)
Definition: imagedata.cpp:614

◆ LogIterations()

void tesseract::LSTMTrainer::LogIterations ( const char *  intro_str,
std::stringstream &  log_msg 
) const

Definition at line 407 of file lstmtrainer.cpp.

408 {
409 log_msg << intro_str
410 << " iteration " << learning_iteration()
411 << "/" << training_iteration()
412 << "/" << sample_iteration();
413}
int learning_iteration() const
Definition: lstmtrainer.h:145

◆ MaintainCheckpoints()

bool tesseract::LSTMTrainer::MaintainCheckpoints ( const TestCallback tester,
std::stringstream &  log_msg 
)

Definition at line 309 of file lstmtrainer.cpp.

310 {
311 PrepareLogMsg(log_msg);
312 double error_rate = CharError();
313 int iteration = learning_iteration();
314 if (iteration >= stall_iteration_ &&
315 error_rate > best_error_rate_ * (1.0 + kSubTrainerMarginFraction) &&
317 // It hasn't got any better in a long while, and is a margin worse than the
318 // best, so go back to the best model and try a different learning rate.
319 StartSubtrainer(log_msg);
320 }
321 SubTrainerResult sub_trainer_result = STR_NONE;
322 if (sub_trainer_ != nullptr) {
323 sub_trainer_result = UpdateSubtrainer(log_msg);
324 if (sub_trainer_result == STR_REPLACED) {
325 // Reset the inputs, as we have overwritten *this.
326 error_rate = CharError();
327 iteration = learning_iteration();
328 PrepareLogMsg(log_msg);
329 }
330 }
331 bool result = true; // Something interesting happened.
332 std::vector<char> rec_model_data;
333 if (error_rate < best_error_rate_) {
334 SaveRecognitionDump(&rec_model_data);
335 log_msg << " New best BCER = " << error_rate;
336 log_msg << UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
337 // If sub_trainer_ is not nullptr, either *this beat it to a new best, or it
338 // just overwrote *this. In either case, we have finished with it.
339 sub_trainer_.reset();
342 log_msg << " Transitioned to stage " << CurrentTrainingStage();
343 }
346 std::string best_model_name = DumpFilename();
347 if (!SaveDataToFile(best_trainer_, best_model_name.c_str())) {
348 log_msg << " failed to write best model:";
349 } else {
350 log_msg << " wrote best model:";
352 }
353 log_msg << best_model_name;
354 }
355 } else if (error_rate > worst_error_rate_) {
356 SaveRecognitionDump(&rec_model_data);
357 log_msg << " New worst BCER = " << error_rate;
358 log_msg << UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
361 // Error rate has ballooned. Go back to the best model.
362 log_msg << "\nDivergence! ";
363 // Copy best_trainer_ before reading it, as it will get overwritten.
364 std::vector<char> revert_data(best_trainer_);
365 if (ReadTrainingDump(revert_data, *this)) {
366 LogIterations("Reverted to", log_msg);
367 ReduceLearningRates(this, log_msg);
368 } else {
369 LogIterations("Failed to Revert at", log_msg);
370 }
371 // If it fails again, we will wait twice as long before reverting again.
372 stall_iteration_ = iteration + 2 * (iteration - learning_iteration());
373 // Re-save the best trainer with the new learning rates and stall
374 // iteration.
376 }
377 } else {
378 // Something interesting happened only if the sub_trainer_ was trained.
379 result = sub_trainer_result != STR_NONE;
380 }
381 if (checkpoint_name_.length() > 0) {
382 // Write a current checkpoint.
383 std::vector<char> checkpoint;
384 if (!SaveTrainingDump(FULL, *this, &checkpoint) ||
385 !SaveDataToFile(checkpoint, checkpoint_name_.c_str())) {
386 log_msg << " failed to write checkpoint.";
387 } else {
388 log_msg << " wrote checkpoint.";
389 }
390 }
391 return result;
392}
@ STR_REPLACED
Definition: lstmtrainer.h:70
const double kSubTrainerMarginFraction
Definition: lstmtrainer.cpp:52
bool SaveDataToFile(const GenericVector< char > &data, const char *filename)
const double kMinDivergenceRate
Definition: lstmtrainer.cpp:47
const double kBestCheckpointFraction
Definition: lstmtrainer.cpp:70
const double kStageTransitionThreshold
Definition: lstmtrainer.cpp:64
bool TransitionTrainingStage(float error_threshold)
std::string UpdateErrorGraph(int iteration, double error_rate, const std::vector< char > &model_data, const TestCallback &tester)
void LogIterations(const char *intro_str, std::stringstream &log_msg) const
double CharError() const
Definition: lstmtrainer.h:133
void StartSubtrainer(std::stringstream &log_msg)
void SaveRecognitionDump(std::vector< char > *data) const
SubTrainerResult UpdateSubtrainer(std::stringstream &log_msg)
int CurrentTrainingStage() const
Definition: lstmtrainer.h:217
std::string DumpFilename() const
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer &trainer, std::vector< char > *data) const
void PrepareLogMsg(std::stringstream &log_msg) const
void ReduceLearningRates(LSTMTrainer *samples_trainer, std::stringstream &log_msg)

◆ MaintainCheckpointsSpecific()

bool tesseract::LSTMTrainer::MaintainCheckpointsSpecific ( int  iteration,
const std::vector< char > *  train_model,
const std::vector< char > *  rec_model,
TestCallback  tester,
std::stringstream &  log_msg 
)

◆ MapRecoder()

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

Definition at line 1074 of file lstmtrainer.cpp.

1075 {
1076 int num_new_codes = recoder_.code_range();
1077 int num_new_unichars = GetUnicharset().size();
1078 std::vector<int> code_map(num_new_codes, -1);
1079 for (int c = 0; c < num_new_codes; ++c) {
1080 int old_code = -1;
1081 // Find all new unichar_ids that recode to something that includes c.
1082 // The <= is to include the null char, which may be beyond the unicharset.
1083 for (int uid = 0; uid <= num_new_unichars; ++uid) {
1084 RecodedCharID codes;
1085 int length = recoder_.EncodeUnichar(uid, &codes);
1086 int code_index = 0;
1087 while (code_index < length && codes(code_index) != c) {
1088 ++code_index;
1089 }
1090 if (code_index == length) {
1091 continue;
1092 }
1093 // The old unicharset must have the same unichar.
1094 int old_uid =
1095 uid < num_new_unichars
1096 ? old_chset.unichar_to_id(GetUnicharset().id_to_unichar(uid))
1097 : old_chset.size() - 1;
1098 if (old_uid == INVALID_UNICHAR_ID) {
1099 continue;
1100 }
1101 // The encoding of old_uid at the same code_index is the old code.
1102 RecodedCharID old_codes;
1103 if (code_index < old_recoder.EncodeUnichar(old_uid, &old_codes)) {
1104 old_code = old_codes(code_index);
1105 break;
1106 }
1107 }
1108 code_map[c] = old_code;
1109 }
1110 return code_map;
1111}
int EncodeUnichar(unsigned unichar_id, RecodedCharID *code) const
size_t size() const
Definition: unicharset.h:355

◆ mutable_training_data()

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

Definition at line 172 of file lstmtrainer.h.

172 {
173 return &training_data_;
174 }

◆ NewSingleError()

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

Definition at line 158 of file lstmtrainer.h.

◆ PrepareForBackward()

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

Definition at line 902 of file lstmtrainer.cpp.

904 {
905 if (trainingdata == nullptr) {
906 tprintf("Null trainingdata.\n");
907 return UNENCODABLE;
908 }
909 // Ensure repeatability of random elements even across checkpoints.
910 bool debug =
912 std::vector<int> truth_labels;
913 if (!EncodeString(trainingdata->transcription(), &truth_labels)) {
914 tprintf("Can't encode transcription: '%s' in language '%s'\n",
915 trainingdata->transcription().c_str(),
916 trainingdata->language().c_str());
917 return UNENCODABLE;
918 }
919 bool upside_down = false;
920 if (randomly_rotate_) {
921 // This ensures consistent training results.
923 upside_down = randomizer_.SignedRand(1.0) > 0.0;
924 if (upside_down) {
925 // Modify the truth labels to match the rotation:
926 // Apart from space and null, increment the label. This changes the
927 // script-id to the same script-id but upside-down.
928 // The labels need to be reversed in order, as the first is now the last.
929 for (auto truth_label : truth_labels) {
930 if (truth_label != UNICHAR_SPACE && truth_label != null_char_) {
931 ++truth_label;
932 }
933 }
934 std::reverse(truth_labels.begin(), truth_labels.end());
935 }
936 }
937 unsigned w = 0;
938 while (w < truth_labels.size() &&
939 (truth_labels[w] == UNICHAR_SPACE || truth_labels[w] == null_char_)) {
940 ++w;
941 }
942 if (w == truth_labels.size()) {
943 tprintf("Blank transcription: %s\n", trainingdata->transcription().c_str());
944 return UNENCODABLE;
945 }
946 float image_scale;
947 NetworkIO inputs;
948 bool invert = trainingdata->boxes().empty();
949 if (!RecognizeLine(*trainingdata, invert ? 0.5f : 0.0f, debug, invert, upside_down,
950 &image_scale, &inputs, fwd_outputs)) {
951 tprintf("Image %s not trainable\n", trainingdata->imagefilename().c_str());
952 return UNENCODABLE;
953 }
954 targets->Resize(*fwd_outputs, network_->NumOutputs());
955 LossType loss_type = OutputLossType();
956 if (loss_type == LT_SOFTMAX) {
957 if (!ComputeTextTargets(*fwd_outputs, truth_labels, targets)) {
958 tprintf("Compute simple targets failed for %s!\n",
959 trainingdata->imagefilename().c_str());
960 return UNENCODABLE;
961 }
962 } else if (loss_type == LT_CTC) {
963 if (!ComputeCTCTargets(truth_labels, fwd_outputs, targets)) {
964 tprintf("Compute CTC targets failed for %s!\n",
965 trainingdata->imagefilename().c_str());
966 return UNENCODABLE;
967 }
968 } else {
969 tprintf("Logistic outputs not implemented yet!\n");
970 return UNENCODABLE;
971 }
972 std::vector<int> ocr_labels;
973 std::vector<int> xcoords;
974 LabelsFromOutputs(*fwd_outputs, &ocr_labels, &xcoords);
975 // CTC does not produce correct target labels to begin with.
976 if (loss_type != LT_CTC) {
977 LabelsFromOutputs(*targets, &truth_labels, &xcoords);
978 }
979 if (!DebugLSTMTraining(inputs, *trainingdata, *fwd_outputs, truth_labels,
980 *targets)) {
981 tprintf("Input width was %d\n", inputs.Width());
982 return UNENCODABLE;
983 }
984 std::string ocr_text = DecodeLabels(ocr_labels);
985 std::string truth_text = DecodeLabels(truth_labels);
986 targets->SubtractAllFromFloat(*fwd_outputs);
987 if (debug_interval_ != 0) {
988 if (truth_text != ocr_text) {
989 tprintf("Iteration %d: BEST OCR TEXT : %s\n", training_iteration(),
990 ocr_text.c_str());
991 }
992 }
993 double char_error = ComputeCharError(truth_labels, ocr_labels);
994 double word_error = ComputeWordError(&truth_text, &ocr_text);
995 double delta_error = ComputeErrorRates(*targets, char_error, word_error);
996 if (debug_interval_ != 0) {
997 tprintf("File %s line %d %s:\n", trainingdata->imagefilename().c_str(),
998 trainingdata->page_number(), delta_error == 0.0 ? "(Perfect)" : "");
999 }
1000 if (delta_error == 0.0) {
1001 return PERFECT;
1002 }
1003 if (targets->AnySuspiciousTruth(kHighConfidence)) {
1004 return HI_PRECISION_ERR;
1005 }
1006 return TRAINABLE;
1007}
@ UNICHAR_SPACE
Definition: unicharset.h:36
const double kHighConfidence
Definition: lstmtrainer.cpp:66
double SignedRand(double range)
Definition: helpers.h:78
void RecognizeLine(const ImageData &image_data, float invert_threshold, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words, int lstm_choice_mode=0, int lstm_choice_amount=5)
int NumOutputs() const
Definition: network.h:125
double ComputeErrorRates(const NetworkIO &deltas, double char_error, double word_error)
bool ComputeCTCTargets(const std::vector< int > &truth_labels, NetworkIO *outputs, NetworkIO *targets)
bool ComputeTextTargets(const NetworkIO &outputs, const std::vector< int > &truth_labels, NetworkIO *targets)
bool DebugLSTMTraining(const NetworkIO &inputs, const ImageData &trainingdata, const NetworkIO &fwd_outputs, const std::vector< int > &truth_labels, const NetworkIO &outputs)
double ComputeCharError(const std::vector< int > &truth_str, const std::vector< int > &ocr_str)

◆ PrepareLogMsg()

void tesseract::LSTMTrainer::PrepareLogMsg ( std::stringstream &  log_msg) const

Definition at line 395 of file lstmtrainer.cpp.

395 {
396 LogIterations("At", log_msg);
397 log_msg << std::fixed << std::setprecision(3)
398 << ", mean rms=" << error_rates_[ET_RMS]
399 << "%, delta=" << error_rates_[ET_DELTA]
400 << "%, BCER train=" << error_rates_[ET_CHAR_ERROR]
401 << "%, BWER train=" << error_rates_[ET_WORD_RECERR]
402 << "%, skip ratio=" << error_rates_[ET_SKIP_RATIO] << "%,";
403}

◆ ReadLocalTrainingDump()

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

Definition at line 1022 of file lstmtrainer.cpp.

1023 {
1024 if (size == 0) {
1025 tprintf("Warning: data size is 0 in LSTMTrainer::ReadLocalTrainingDump\n");
1026 return false;
1027 }
1028 TFile fp;
1029 fp.Open(data, size);
1030 return DeSerialize(mgr, &fp);
1031}
bool DeSerialize(const TessdataManager *mgr, TFile *fp)

◆ ReadSizedTrainingDump()

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

Definition at line 307 of file lstmtrainer.h.

308 {
309 return trainer.ReadLocalTrainingDump(&mgr_, data, size);
310 }

◆ ReadTrainingDump()

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

Definition at line 300 of file lstmtrainer.h.

301 {
302 if (data.empty()) {
303 return false;
304 }
305 return ReadSizedTrainingDump(&data[0], data.size(), trainer);
306 }
bool ReadSizedTrainingDump(const char *data, int size, LSTMTrainer &trainer) const
Definition: lstmtrainer.h:307

◆ ReduceLayerLearningRates()

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

Definition at line 694 of file lstmtrainer.cpp.

695 {
696 enum WhichWay {
697 LR_DOWN, // Learning rate will go down by factor.
698 LR_SAME, // Learning rate will stay the same.
699 LR_COUNT // Size of arrays.
700 };
701 std::vector<std::string> layers = EnumerateLayers();
702 int num_layers = layers.size();
703 std::vector<int> num_weights(num_layers);
704 std::vector<TFloat> bad_sums[LR_COUNT];
705 std::vector<TFloat> ok_sums[LR_COUNT];
706 for (int i = 0; i < LR_COUNT; ++i) {
707 bad_sums[i].resize(num_layers, 0.0);
708 ok_sums[i].resize(num_layers, 0.0);
709 }
710 auto momentum_factor = 1 / (1 - momentum_);
711 std::vector<char> orig_trainer;
712 samples_trainer->SaveTrainingDump(LIGHT, *this, &orig_trainer);
713 for (int i = 0; i < num_layers; ++i) {
714 Network *layer = GetLayer(layers[i]);
715 num_weights[i] = layer->IsTraining() ? layer->num_weights() : 0;
716 }
717 int iteration = sample_iteration();
718 for (int s = 0; s < num_samples; ++s) {
719 // Which way will we modify the learning rate?
720 for (int ww = 0; ww < LR_COUNT; ++ww) {
721 // Transfer momentum to learning rate and adjust by the ww factor.
722 auto ww_factor = momentum_factor;
723 if (ww == LR_DOWN) {
724 ww_factor *= factor;
725 }
726 // Make a copy of *this, so we can mess about without damaging anything.
727 LSTMTrainer copy_trainer;
728 samples_trainer->ReadTrainingDump(orig_trainer, copy_trainer);
729 // Clear the updates, doing nothing else.
730 copy_trainer.network_->Update(0.0, 0.0, 0.0, 0);
731 // Adjust the learning rate in each layer.
732 for (int i = 0; i < num_layers; ++i) {
733 if (num_weights[i] == 0) {
734 continue;
735 }
736 copy_trainer.ScaleLayerLearningRate(layers[i], ww_factor);
737 }
738 copy_trainer.SetIteration(iteration);
739 // Train on the sample, but keep the update in updates_ instead of
740 // applying to the weights.
741 const ImageData *trainingdata =
742 copy_trainer.TrainOnLine(samples_trainer, true);
743 if (trainingdata == nullptr) {
744 continue;
745 }
746 // We'll now use this trainer again for each layer.
747 std::vector<char> updated_trainer;
748 samples_trainer->SaveTrainingDump(LIGHT, copy_trainer, &updated_trainer);
749 for (int i = 0; i < num_layers; ++i) {
750 if (num_weights[i] == 0) {
751 continue;
752 }
753 LSTMTrainer layer_trainer;
754 samples_trainer->ReadTrainingDump(updated_trainer, layer_trainer);
755 Network *layer = layer_trainer.GetLayer(layers[i]);
756 // Update the weights in just the layer, using Adam if enabled.
757 layer->Update(0.0, momentum_, adam_beta_,
758 layer_trainer.training_iteration_ + 1);
759 // Zero the updates matrix again.
760 layer->Update(0.0, 0.0, 0.0, 0);
761 // Train again on the same sample, again holding back the updates.
762 layer_trainer.TrainOnLine(trainingdata, true);
763 // Count the sign changes in the updates in layer vs in copy_trainer.
764 float before_bad = bad_sums[ww][i];
765 float before_ok = ok_sums[ww][i];
766 layer->CountAlternators(*copy_trainer.GetLayer(layers[i]),
767 &ok_sums[ww][i], &bad_sums[ww][i]);
768 float bad_frac =
769 bad_sums[ww][i] + ok_sums[ww][i] - before_bad - before_ok;
770 if (bad_frac > 0.0f) {
771 bad_frac = (bad_sums[ww][i] - before_bad) / bad_frac;
772 }
773 }
774 }
775 ++iteration;
776 }
777 int num_lowered = 0;
778 for (int i = 0; i < num_layers; ++i) {
779 if (num_weights[i] == 0) {
780 continue;
781 }
782 Network *layer = GetLayer(layers[i]);
783 float lr = GetLayerLearningRate(layers[i]);
784 TFloat total_down = bad_sums[LR_DOWN][i] + ok_sums[LR_DOWN][i];
785 TFloat total_same = bad_sums[LR_SAME][i] + ok_sums[LR_SAME][i];
786 TFloat frac_down = bad_sums[LR_DOWN][i] / total_down;
787 TFloat frac_same = bad_sums[LR_SAME][i] / total_same;
788 tprintf("Layer %d=%s: lr %g->%g%%, lr %g->%g%%", i, layer->name().c_str(),
789 lr * factor, 100.0 * frac_down, lr, 100.0 * frac_same);
790 if (frac_down < frac_same * kImprovementFraction) {
791 tprintf(" REDUCED\n");
792 ScaleLayerLearningRate(layers[i], factor);
793 ++num_lowered;
794 } else {
795 tprintf(" SAME\n");
796 }
797 }
798 if (num_lowered == 0) {
799 // Just lower everything to make sure.
800 for (int i = 0; i < num_layers; ++i) {
801 if (num_weights[i] > 0) {
802 ScaleLayerLearningRate(layers[i], factor);
803 ++num_lowered;
804 }
805 }
806 }
807 return num_lowered;
808}
const double kImprovementFraction
Definition: lstmtrainer.cpp:68
double TFloat
Definition: tesstypes.h:39
void ScaleLayerLearningRate(const std::string &id, double factor)
std::vector< std::string > EnumerateLayers() const
float GetLayerLearningRate(const std::string &id) const
Network * GetLayer(const std::string &id) const

◆ ReduceLearningRates()

void tesseract::LSTMTrainer::ReduceLearningRates ( LSTMTrainer samples_trainer,
std::stringstream &  log_msg 
)

Definition at line 675 of file lstmtrainer.cpp.

676 {
678 int num_reduced = ReduceLayerLearningRates(
680 log_msg << "\nReduced learning rate on layers: " << num_reduced;
681 } else {
683 log_msg << "\nReduced learning rate to :" << learning_rate_;
684 }
685 log_msg << "\n";
686}
const double kLearningRateDecay
Definition: lstmtrainer.cpp:54
@ NF_LAYER_SPECIFIC_LR
Definition: network.h:85
const int kNumAdjustmentIterations
Definition: lstmtrainer.cpp:56
void ScaleLearningRate(double factor)
bool TestFlag(NetworkFlags flag) const
Definition: network.h:146
int ReduceLayerLearningRates(TFloat factor, int num_samples, LSTMTrainer *samples_trainer)

◆ RollErrorBuffers()

void tesseract::LSTMTrainer::RollErrorBuffers ( )
protected

Definition at line 1405 of file lstmtrainer.cpp.

1405 {
1407 if (NewSingleError(ET_DELTA) > 0.0) {
1409 } else {
1411 }
1413 if (debug_interval_ != 0) {
1414 tprintf("Mean rms=%g%%, delta=%g%%, train=%g%%(%g%%), skip ratio=%g%%\n",
1418 }
1419}
double NewSingleError(ErrorTypes type) const
Definition: lstmtrainer.h:158

◆ SaveRecognitionDump()

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

Definition at line 1043 of file lstmtrainer.cpp.

1043 {
1044 TFile fp;
1045 fp.OpenWrite(data);
1049}
@ TS_TEMP_DISABLE
Definition: network.h:95
@ TS_RE_ENABLE
Definition: network.h:97
bool Serialize(const TessdataManager *mgr, TFile *fp) const

◆ SaveTraineddata()

bool tesseract::LSTMTrainer::SaveTraineddata ( const char *  filename)

Definition at line 1034 of file lstmtrainer.cpp.

1034 {
1035 std::vector<char> recognizer_data;
1036 SaveRecognitionDump(&recognizer_data);
1037 mgr_.OverwriteEntry(TESSDATA_LSTM, &recognizer_data[0],
1038 recognizer_data.size());
1039 return mgr_.SaveFile(filename, SaveDataToFile);
1040}
void OverwriteEntry(TessdataType type, const char *data, int size)
bool SaveFile(const char *filename, FileWriter writer) const

◆ SaveTrainingDump()

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

Definition at line 1013 of file lstmtrainer.cpp.

1015 {
1016 TFile fp;
1017 fp.OpenWrite(data);
1018 return trainer.Serialize(serialize_amount, &mgr_, &fp);
1019}

◆ Serialize()

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

Definition at line 427 of file lstmtrainer.cpp.

428 {
429 if (!LSTMRecognizer::Serialize(mgr, fp)) {
430 return false;
431 }
432 if (!fp->Serialize(&learning_iteration_)) {
433 return false;
434 }
435 if (!fp->Serialize(&prev_sample_iteration_)) {
436 return false;
437 }
438 if (!fp->Serialize(&perfect_delay_)) {
439 return false;
440 }
441 if (!fp->Serialize(&last_perfect_training_iteration_)) {
442 return false;
443 }
444 for (const auto &error_buffer : error_buffers_) {
445 if (!fp->Serialize(error_buffer)) {
446 return false;
447 }
448 }
449 if (!fp->Serialize(&error_rates_[0], countof(error_rates_))) {
450 return false;
451 }
452 if (!fp->Serialize(&training_stage_)) {
453 return false;
454 }
455 uint8_t amount = serialize_amount;
456 if (!fp->Serialize(&amount)) {
457 return false;
458 }
459 if (serialize_amount == LIGHT) {
460 return true; // We are done.
461 }
462 if (!fp->Serialize(&best_error_rate_)) {
463 return false;
464 }
465 if (!fp->Serialize(&best_error_rates_[0], countof(best_error_rates_))) {
466 return false;
467 }
468 if (!fp->Serialize(&best_iteration_)) {
469 return false;
470 }
471 if (!fp->Serialize(&worst_error_rate_)) {
472 return false;
473 }
474 if (!fp->Serialize(&worst_error_rates_[0], countof(worst_error_rates_))) {
475 return false;
476 }
477 if (!fp->Serialize(&worst_iteration_)) {
478 return false;
479 }
480 if (!fp->Serialize(&stall_iteration_)) {
481 return false;
482 }
483 if (!fp->Serialize(best_model_data_)) {
484 return false;
485 }
486 if (!fp->Serialize(worst_model_data_)) {
487 return false;
488 }
489 if (serialize_amount != NO_BEST_TRAINER && !fp->Serialize(best_trainer_)) {
490 return false;
491 }
492 std::vector<char> sub_data;
493 if (sub_trainer_ != nullptr &&
494 !SaveTrainingDump(LIGHT, *sub_trainer_, &sub_data)) {
495 return false;
496 }
497 if (!fp->Serialize(sub_data)) {
498 return false;
499 }
500 if (!fp->Serialize(best_error_history_)) {
501 return false;
502 }
503 if (!fp->Serialize(best_error_iterations_)) {
504 return false;
505 }
506 return fp->Serialize(&improvement_steps_);
507}

◆ set_perfect_delay()

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

Definition at line 151 of file lstmtrainer.h.

151 {
152 perfect_delay_ = delay;
153 }

◆ SetNullChar()

void tesseract::LSTMTrainer::SetNullChar ( )
protected

Definition at line 1128 of file lstmtrainer.cpp.

1128 {
1130 : GetUnicharset().size();
1131 RecodedCharID code;
1133 null_char_ = code(0);
1134}
@ UNICHAR_BROKEN
Definition: unicharset.h:38
bool has_special_codes() const
Definition: unicharset.h:756

◆ SetupCheckpointInfo()

void tesseract::LSTMTrainer::SetupCheckpointInfo ( )

◆ StartSubtrainer()

void tesseract::LSTMTrainer::StartSubtrainer ( std::stringstream &  log_msg)

Definition at line 605 of file lstmtrainer.cpp.

605 {
606 sub_trainer_ = std::make_unique<LSTMTrainer>();
608 log_msg << " Failed to revert to previous best for trial!";
609 sub_trainer_.reset();
610 } else {
611 log_msg << " Trial sub_trainer_ from iteration "
612 << sub_trainer_->training_iteration();
613 // Reduce learning rate so it doesn't diverge this time.
614 sub_trainer_->ReduceLearningRates(this, log_msg);
615 // If it fails again, we will wait twice as long before reverting again.
616 int stall_offset =
617 learning_iteration() - sub_trainer_->learning_iteration();
618 stall_iteration_ = learning_iteration() + 2 * stall_offset;
619 sub_trainer_->stall_iteration_ = stall_iteration_;
620 // Re-save the best trainer with the new learning rates and stall iteration.
622 }
623}

◆ training_data()

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

Definition at line 169 of file lstmtrainer.h.

169 {
170 return training_data_;
171 }

◆ TrainOnLine() [1/2]

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

Definition at line 869 of file lstmtrainer.cpp.

870 {
871 NetworkIO fwd_outputs, targets;
872 Trainability trainable =
873 PrepareForBackward(trainingdata, &fwd_outputs, &targets);
875 if (trainable == UNENCODABLE || trainable == NOT_BOXED) {
876 return trainable; // Sample was unusable.
877 }
878 bool debug =
880 // Run backprop on the output.
881 NetworkIO bp_deltas;
882 if (network_->IsTraining() &&
883 (trainable != PERFECT ||
886 network_->Backward(debug, targets, &scratch_space_, &bp_deltas);
889 }
890#ifndef GRAPHICS_DISABLED
891 if (debug_interval_ == 1 && debug_win_ != nullptr) {
893 }
894#endif // !GRAPHICS_DISABLED
895 // Roll the memory of past means.
897 return trainable;
898}
@ SVET_CLICK
Definition: scrollview.h:56
NetworkScratch scratch_space_
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)=0
bool IsTraining() const
Definition: network.h:113
virtual void Update(float learning_rate, float momentum, float adam_beta, int num_samples)
Definition: network.h:235
std::unique_ptr< SVEvent > AwaitEvent(SVEventType type)
Definition: scrollview.cpp:432

◆ TrainOnLine() [2/2]

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

Definition at line 268 of file lstmtrainer.h.

268 {
269 int sample_index = sample_iteration();
270 const ImageData *image =
271 samples_trainer->training_data_.GetPageBySerial(sample_index);
272 if (image != nullptr) {
273 Trainability trainable = TrainOnLine(image, batch);
274 if (trainable == UNENCODABLE || trainable == NOT_BOXED) {
275 return nullptr; // Sample was unusable.
276 }
277 } else {
279 }
280 return image;
281 }
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
Definition: lstmtrainer.h:268

◆ TransitionTrainingStage()

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

Definition at line 417 of file lstmtrainer.cpp.

417 {
418 if (best_error_rate_ < error_threshold &&
421 return true;
422 }
423 return false;
424}

◆ TryLoadingCheckpoint()

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

Definition at line 105 of file lstmtrainer.cpp.

106 {
107 std::vector<char> data;
108 if (!LoadDataFromFile(filename, &data)) {
109 return false;
110 }
111 tprintf("Loaded file %s, unpacking...\n", filename);
112 if (!ReadTrainingDump(data, *this)) {
113 return false;
114 }
115 if (IsIntMode()) {
116 tprintf("Error, %s is an integer (fast) model, cannot continue training\n",
117 filename);
118 return false;
119 }
120 if (((old_traineddata == nullptr || *old_traineddata == '\0') &&
122 filename == old_traineddata) {
123 return true; // Normal checkpoint load complete.
124 }
125 tprintf("Code range changed from %d to %d!\n", network_->NumOutputs(),
127 if (old_traineddata == nullptr || *old_traineddata == '\0') {
128 tprintf("Must supply the old traineddata for code conversion!\n");
129 return false;
130 }
131 TessdataManager old_mgr;
132 ASSERT_HOST(old_mgr.Init(old_traineddata));
133 TFile fp;
134 if (!old_mgr.GetComponent(TESSDATA_LSTM_UNICHARSET, &fp)) {
135 return false;
136 }
137 UNICHARSET old_chset;
138 if (!old_chset.load_from_file(&fp, false)) {
139 return false;
140 }
141 if (!old_mgr.GetComponent(TESSDATA_LSTM_RECODER, &fp)) {
142 return false;
143 }
144 UnicharCompress old_recoder;
145 if (!old_recoder.DeSerialize(&fp)) {
146 return false;
147 }
148 std::vector<int> code_map = MapRecoder(old_chset, old_recoder);
149 // Set the null_char_ to the new value.
150 int old_null_char = null_char_;
151 SetNullChar();
152 // Map the softmax(s) in the network.
153 network_->RemapOutputs(old_recoder.code_range(), code_map);
154 tprintf("Previous null char=%d mapped to %d\n", old_null_char, null_char_);
155 return true;
156}
@ TESSDATA_LSTM_UNICHARSET
@ TESSDATA_LSTM_RECODER
virtual int RemapOutputs(int old_no, const std::vector< int > &code_map)
Definition: network.h:190
std::vector< int > MapRecoder(const UNICHARSET &old_chset, const UnicharCompress &old_recoder) const

◆ UpdateErrorBuffer()

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

Definition at line 1389 of file lstmtrainer.cpp.

1389 {
1391 error_buffers_[type][index] = new_error;
1392 // Compute the mean error.
1393 int mean_count =
1394 std::min<int>(training_iteration_ + 1, error_buffers_[type].size());
1395 double buffer_sum = 0.0;
1396 for (int i = 0; i < mean_count; ++i) {
1397 buffer_sum += error_buffers_[type][i];
1398 }
1399 double mean = buffer_sum / mean_count;
1400 // Trim precision to 1/1000 of 1%.
1401 error_rates_[type] = IntCastRounded(100000.0 * mean) / 1000.0;
1402}
int IntCastRounded(double x)
Definition: helpers.h:170

◆ UpdateErrorGraph()

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

Definition at line 1425 of file lstmtrainer.cpp.

1427 {
1428 if (error_rate > best_error_rate_ &&
1429 iteration < best_iteration_ + kErrorGraphInterval) {
1430 // Too soon to record a new point.
1431 if (tester != nullptr && !worst_model_data_.empty()) {
1433 worst_model_data_.size());
1434 return tester(worst_iteration_, nullptr, mgr_, CurrentTrainingStage());
1435 } else {
1436 return "";
1437 }
1438 }
1439 std::string result;
1440 // NOTE: there are 2 asymmetries here:
1441 // 1. We are computing the global minimum, but the local maximum in between.
1442 // 2. If the tester returns an empty string, indicating that it is busy,
1443 // call it repeatedly on new local maxima to test the previous min, but
1444 // not the other way around, as there is little point testing the maxima
1445 // between very frequent minima.
1446 if (error_rate < best_error_rate_) {
1447 // This is a new (global) minimum.
1448 if (tester != nullptr && !worst_model_data_.empty()) {
1450 worst_model_data_.size());
1451 result = tester(worst_iteration_, worst_error_rates_, mgr_,
1453 worst_model_data_.clear();
1454 best_model_data_ = model_data;
1455 }
1456 best_error_rate_ = error_rate;
1458 best_iteration_ = iteration;
1459 best_error_history_.push_back(error_rate);
1460 best_error_iterations_.push_back(iteration);
1461 // Compute 2% decay time.
1462 double two_percent_more = error_rate + 2.0;
1463 int i;
1464 for (i = best_error_history_.size() - 1;
1465 i >= 0 && best_error_history_[i] < two_percent_more; --i) {
1466 }
1467 int old_iteration = i >= 0 ? best_error_iterations_[i] : 0;
1468 improvement_steps_ = iteration - old_iteration;
1469 tprintf("2 Percent improvement time=%d, best error was %g @ %d\n",
1470 improvement_steps_, i >= 0 ? best_error_history_[i] : 100.0,
1471 old_iteration);
1472 } else if (error_rate > best_error_rate_) {
1473 // This is a new (local) maximum.
1474 if (tester != nullptr) {
1475 if (!best_model_data_.empty()) {
1477 best_model_data_.size());
1478 result = tester(best_iteration_, best_error_rates_, mgr_,
1480 } else if (!worst_model_data_.empty()) {
1481 // Allow for multiple data points with "worst" error rate.
1483 worst_model_data_.size());
1484 result = tester(worst_iteration_, worst_error_rates_, mgr_,
1486 }
1487 if (result.length() > 0) {
1488 best_model_data_.clear();
1489 }
1490 worst_model_data_ = model_data;
1491 }
1492 }
1493 worst_error_rate_ = error_rate;
1495 worst_iteration_ = iteration;
1496 return result;
1497}
const int kErrorGraphInterval
Definition: lstmtrainer.cpp:58

◆ UpdateSubtrainer()

SubTrainerResult tesseract::LSTMTrainer::UpdateSubtrainer ( std::stringstream &  log_msg)

Definition at line 633 of file lstmtrainer.cpp.

633 {
634 double training_error = CharError();
635 double sub_error = sub_trainer_->CharError();
636 double sub_margin = (training_error - sub_error) / sub_error;
637 if (sub_margin >= kSubTrainerMarginFraction) {
638 log_msg << " sub_trainer=" << sub_error
639 << " margin=" << 100.0 * sub_margin << "\n";
640 // Catch up to current iteration.
641 int end_iteration = training_iteration();
642 while (sub_trainer_->training_iteration() < end_iteration &&
643 sub_margin >= kSubTrainerMarginFraction) {
644 int target_iteration =
645 sub_trainer_->training_iteration() + kNumPagesPerBatch;
646 while (sub_trainer_->training_iteration() < target_iteration) {
647 sub_trainer_->TrainOnLine(this, false);
648 }
649 std::stringstream batch_log("Sub:");
650 batch_log.imbue(std::locale::classic());
651 sub_trainer_->PrepareLogMsg(batch_log);
652 batch_log << "\n";
653 tprintf("UpdateSubtrainer:%s", batch_log.str().c_str());
654 log_msg << batch_log.str();
655 sub_error = sub_trainer_->CharError();
656 sub_margin = (training_error - sub_error) / sub_error;
657 }
658 if (sub_error < best_error_rate_ &&
659 sub_margin >= kSubTrainerMarginFraction) {
660 // The sub_trainer_ has won the race to a new best. Switch to it.
661 std::vector<char> updated_trainer;
662 SaveTrainingDump(LIGHT, *sub_trainer_, &updated_trainer);
663 ReadTrainingDump(updated_trainer, *this);
664 log_msg << " Sub trainer wins at iteration "
665 << training_iteration() << "\n";
666 return STR_REPLACED;
667 }
668 return STR_UPDATED;
669 }
670 return STR_NONE;
671}
const int kNumPagesPerBatch
Definition: lstmtrainer.cpp:60

Member Data Documentation

◆ align_win_

ScrollView* tesseract::LSTMTrainer::align_win_
protected

Definition at line 408 of file lstmtrainer.h.

◆ best_error_history_

std::vector<double> tesseract::LSTMTrainer::best_error_history_
protected

Definition at line 462 of file lstmtrainer.h.

◆ best_error_iterations_

std::vector<int32_t> tesseract::LSTMTrainer::best_error_iterations_
protected

Definition at line 463 of file lstmtrainer.h.

◆ best_error_rate_

double tesseract::LSTMTrainer::best_error_rate_
protected

Definition at line 435 of file lstmtrainer.h.

◆ best_error_rates_

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

Definition at line 437 of file lstmtrainer.h.

◆ best_iteration_

int tesseract::LSTMTrainer::best_iteration_
protected

Definition at line 439 of file lstmtrainer.h.

◆ best_model_data_

std::vector<char> tesseract::LSTMTrainer::best_model_data_
protected

Definition at line 449 of file lstmtrainer.h.

◆ best_model_name_

std::string tesseract::LSTMTrainer::best_model_name_
protected

Definition at line 428 of file lstmtrainer.h.

◆ best_trainer_

std::vector<char> tesseract::LSTMTrainer::best_trainer_
protected

Definition at line 452 of file lstmtrainer.h.

◆ checkpoint_iteration_

int tesseract::LSTMTrainer::checkpoint_iteration_
protected

Definition at line 419 of file lstmtrainer.h.

◆ checkpoint_name_

std::string tesseract::LSTMTrainer::checkpoint_name_
protected

Definition at line 423 of file lstmtrainer.h.

◆ ctc_win_

ScrollView* tesseract::LSTMTrainer::ctc_win_
protected

Definition at line 412 of file lstmtrainer.h.

◆ debug_interval_

int tesseract::LSTMTrainer::debug_interval_
protected

Definition at line 417 of file lstmtrainer.h.

◆ error_buffers_

std::vector<double> tesseract::LSTMTrainer::error_buffers_[ET_COUNT]
protected

Definition at line 484 of file lstmtrainer.h.

◆ error_rate_of_last_saved_best_

float tesseract::LSTMTrainer::error_rate_of_last_saved_best_
protected

Definition at line 457 of file lstmtrainer.h.

◆ error_rates_

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

Definition at line 486 of file lstmtrainer.h.

◆ improvement_steps_

int32_t tesseract::LSTMTrainer::improvement_steps_
protected

Definition at line 465 of file lstmtrainer.h.

◆ kRollingBufferSize_

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

Definition at line 483 of file lstmtrainer.h.

◆ last_perfect_training_iteration_

int tesseract::LSTMTrainer::last_perfect_training_iteration_
protected

Definition at line 480 of file lstmtrainer.h.

◆ learning_iteration_

int tesseract::LSTMTrainer::learning_iteration_
protected

Definition at line 469 of file lstmtrainer.h.

◆ mgr_

TessdataManager tesseract::LSTMTrainer::mgr_
protected

Definition at line 488 of file lstmtrainer.h.

◆ model_base_

std::string tesseract::LSTMTrainer::model_base_
protected

Definition at line 421 of file lstmtrainer.h.

◆ num_training_stages_

int tesseract::LSTMTrainer::num_training_stages_
protected

Definition at line 430 of file lstmtrainer.h.

◆ perfect_delay_

int tesseract::LSTMTrainer::perfect_delay_
protected

Definition at line 477 of file lstmtrainer.h.

◆ prev_sample_iteration_

int tesseract::LSTMTrainer::prev_sample_iteration_
protected

Definition at line 471 of file lstmtrainer.h.

◆ randomly_rotate_

bool tesseract::LSTMTrainer::randomly_rotate_
protected

Definition at line 425 of file lstmtrainer.h.

◆ recon_win_

ScrollView* tesseract::LSTMTrainer::recon_win_
protected

Definition at line 414 of file lstmtrainer.h.

◆ stall_iteration_

int tesseract::LSTMTrainer::stall_iteration_
protected

Definition at line 447 of file lstmtrainer.h.

◆ sub_trainer_

std::unique_ptr<LSTMTrainer> tesseract::LSTMTrainer::sub_trainer_
protected

Definition at line 455 of file lstmtrainer.h.

◆ target_win_

ScrollView* tesseract::LSTMTrainer::target_win_
protected

Definition at line 410 of file lstmtrainer.h.

◆ training_data_

DocumentCache tesseract::LSTMTrainer::training_data_
protected

Definition at line 426 of file lstmtrainer.h.

◆ training_stage_

int tesseract::LSTMTrainer::training_stage_
protected

Definition at line 459 of file lstmtrainer.h.

◆ worst_error_rate_

double tesseract::LSTMTrainer::worst_error_rate_
protected

Definition at line 441 of file lstmtrainer.h.

◆ worst_error_rates_

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

Definition at line 443 of file lstmtrainer.h.

◆ worst_iteration_

int tesseract::LSTMTrainer::worst_iteration_
protected

Definition at line 445 of file lstmtrainer.h.

◆ worst_model_data_

std::vector<char> tesseract::LSTMTrainer::worst_model_data_
protected

Definition at line 450 of file lstmtrainer.h.


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