18 #define _USE_MATH_DEFINES // needed to get definition of M_SQRT1_2 22 #include "config_auto.h" 28 #include "allheaders.h" 36 #ifdef INCLUDE_TENSORFLOW 75 : randomly_rotate_(false),
83 sub_trainer_(nullptr) {
91 const char* model_base,
const char* checkpoint_name,
92 int debug_interval, int64_t max_memory)
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),
130 const char* old_traineddata) {
133 tprintf(
"Loaded file %s, unpacking...\n", filename);
136 tprintf(
"Error, %s is an integer (fast) model, cannot continue training\n", filename);
140 if (((old_traineddata ==
nullptr || *old_traineddata ==
'\0') &&
142 filename == old_traineddata) {
147 if (old_traineddata ==
nullptr || *old_traineddata ==
'\0') {
148 tprintf(
"Must supply the old traineddata for code conversion!\n");
160 std::vector<int> code_map =
MapRecoder(old_chset, old_recoder);
177 int net_flags,
float weight_range,
178 float learning_rate,
float momentum,
186 append_index, net_flags, weight_range,
191 tprintf(
"Built network:%s from request %s\n",
194 "Training parameters:\n Debug interval = %d," 195 " weights = %g, learning rate = %g, momentum=%g\n",
203 #ifdef INCLUDE_TENSORFLOW 206 TFNetwork* tf_net =
new TFNetwork(
"TensorFlow");
209 tprintf(
"InitFromProtoStr failed!!\n");
233 for (
int i = 0; i <
ET_COUNT; ++i) {
246 const ImageData* trainingdata,
int iteration,
double min_dict_ratio,
247 double dict_ratio_step,
double max_dict_ratio,
double min_cert_offset,
248 double cert_offset_step,
double max_cert_offset,
STRING* results) {
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) {
274 search.ExtractBestPathAsLabels(&ocr_labels, &xcoords);
279 if ((r == min_dict_ratio && c == min_cert_offset) ||
280 !std::isfinite(word_error)) {
283 tprintf(
"r=%g, c=%g, truth=%s, ocr=%s, wderr=%g, truth[0]=%d\n", r, c,
304 bool randomly_rotate) {
340 *log_msg +=
UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
353 *log_msg +=
" failed to write best model:";
355 *log_msg +=
" wrote best model:";
358 *log_msg += best_model_name;
363 *log_msg +=
UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
367 *log_msg +=
"\nDivergence! ";
384 result = sub_trainer_result !=
STR_NONE;
392 *log_msg +=
" failed to write checkpoint.";
394 *log_msg +=
" wrote checkpoint.";
415 *log_msg += intro_str;
441 if (!error_buffer.Serialize(fp))
return false;
445 uint8_t amount = serialize_amount;
446 if (!fp->
Serialize(&amount))
return false;
447 if (serialize_amount ==
LIGHT)
return true;
462 if (!sub_data.
Serialize(fp))
return false;
476 tprintf(
"Warning: LSTMTrainer deserialized an LSTMRecognizer!\n");
485 if (!error_buffer.DeSerialize(fp))
return false;
491 if (amount ==
LIGHT)
return true;
505 if (sub_data.
empty()) {
523 *log_msg +=
" Failed to revert to previous best for trial!";
527 log_msg->
add_str_int(
" Trial sub_trainer_ from iteration ",
552 double sub_margin = (training_error - sub_error) / sub_error;
561 int target_iteration =
566 STRING batch_log =
"Sub:";
570 *log_msg += batch_log;
572 sub_margin = (training_error - sub_error) / sub_error;
580 log_msg->
add_str_int(
" Sub trainer wins at iteration ",
597 log_msg->
add_str_int(
"\nReduced learning rate on layers: ", num_reduced);
619 int num_layers = layers.
size();
624 for (
int i = 0; i < LR_COUNT; ++i) {
628 double momentum_factor = 1.0 / (1.0 -
momentum_);
631 for (
int i = 0; i < num_layers; ++i) {
636 for (
int s = 0; s < num_samples; ++s) {
638 for (
int ww = 0; ww < LR_COUNT; ++ww) {
640 float ww_factor = momentum_factor;
641 if (ww == LR_DOWN) ww_factor *= factor;
648 for (
int i = 0; i < num_layers; ++i) {
649 if (num_weights[i] == 0)
continue;
657 if (trainingdata ==
nullptr)
continue;
661 for (
int i = 0; i < num_layers; ++i) {
662 if (num_weights[i] == 0)
continue;
670 layer->
Update(0.0, 0.0, 0.0, 0);
674 float before_bad = bad_sums[ww][i];
675 float before_ok = ok_sums[ww][i];
677 &ok_sums[ww][i], &bad_sums[ww][i]);
679 bad_sums[ww][i] + ok_sums[ww][i] - before_bad - before_ok;
681 bad_frac = (bad_sums[ww][i] - before_bad) / bad_frac;
687 for (
int i = 0; i < num_layers; ++i) {
688 if (num_weights[i] == 0)
continue;
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;
696 lr * factor, 100.0 * frac_down, lr, 100.0 * frac_same);
705 if (num_lowered == 0) {
707 for (
int i = 0; i < num_layers; ++i) {
708 if (num_weights[i] > 0) {
724 tprintf(
"Empty truth string!\n");
732 if (unicharset.
encode_string(cleaned.c_str(),
true, &internal_labels,
nullptr,
735 for (
int i = 0; i < internal_labels.
size(); ++i) {
736 if (recoder !=
nullptr) {
741 for (
int j = 0; j < len; ++j) {
755 if (success)
return true;
757 tprintf(
"Encoding of string failed! Failure bytes:");
758 while (err_index < cleaned.size()) {
759 tprintf(
" %x", cleaned[err_index++]);
788 #ifndef GRAPHICS_DISABLED 792 #endif // GRAPHICS_DISABLED 803 if (trainingdata ==
nullptr) {
804 tprintf(
"Null trainingdata.\n");
812 tprintf(
"Can't encode transcription: '%s' in language '%s'\n",
817 bool upside_down =
false;
827 for (
int c = 0; c < truth_labels.
size(); ++c) {
835 while (w < truth_labels.
size() &&
838 if (w == truth_labels.
size()) {
839 tprintf(
"Blank transcription: %s\n",
846 if (!
RecognizeLine(*trainingdata, invert, debug, invert, upside_down,
847 &image_scale, &inputs, fwd_outputs)) {
848 tprintf(
"Image not trainable\n");
855 tprintf(
"Compute simple targets failed!\n");
858 }
else if (loss_type ==
LT_CTC) {
860 tprintf(
"Compute CTC targets failed!\n");
864 tprintf(
"Logistic outputs not implemented yet!\n");
871 if (loss_type !=
LT_CTC) {
883 if (truth_text != ocr_text) {
884 tprintf(
"Iteration %d: BEST OCR TEXT : %s\n",
893 trainingdata->
page_number(), delta_error == 0.0 ?
"(Perfect)" :
"");
895 if (delta_error == 0.0)
return PERFECT;
914 const char* data,
int size) {
916 tprintf(
"Warning: data size is 0 in LSTMTrainer::ReadLocalTrainingDump\n");
929 recognizer_data.
size());
948 filename +=
".checkpoint";
965 std::vector<int> code_map(num_new_codes, -1);
966 for (
int c = 0; c < num_new_codes; ++c) {
970 for (
int uid = 0; uid <= num_new_unichars; ++uid) {
974 while (code_index < length && codes(code_index) != c) ++code_index;
975 if (code_index == length)
continue;
978 uid < num_new_unichars
980 : old_chset.
size() - 1;
981 if (old_uid == INVALID_UNICHAR_ID)
continue;
984 if (code_index < old_recoder.
EncodeUnichar(old_uid, &old_codes)) {
985 old_code = old_codes(code_index);
989 code_map[c] = old_code;
1002 "Must provide a traineddata containing lstm_unicharset and" 1003 " lstm_recoder!\n" !=
nullptr);
1039 if (truth_text.
string() ==
nullptr || truth_text.
length() <= 0) {
1040 tprintf(
"Empty truth string at decode time!\n");
1049 tprintf(
"Iteration %d: GROUND TRUTH : %s\n",
1051 if (truth_text != text) {
1052 tprintf(
"Iteration %d: ALIGNED TRUTH : %s\n",
1056 tprintf(
"TRAINING activation path for truth string %s\n",
1071 const char* window_name,
ScrollView** window) {
1072 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics. 1073 int width = targets.
Width();
1077 for (
int c = 0; c < num_features; ++c) {
1079 (*window)->Pen(static_cast<ScrollView::Color>(color));
1081 for (
int t = 0; t < width; ++t) {
1082 double target = targets.
f(t)[c];
1086 (*window)->SetCursor(t - 1, 0);
1089 (*window)->DrawTo(t, target);
1090 }
else if (start_t >= 0) {
1091 (*window)->DrawTo(t, 0);
1092 (*window)->DrawTo(start_t - 1, 0);
1097 (*window)->DrawTo(width, 0);
1098 (*window)->DrawTo(start_t - 1, 0);
1101 (*window)->Update();
1102 #endif // GRAPHICS_DISABLED 1110 if (truth_labels.
size() > targets->
Width()) {
1111 tprintf(
"Error: transcription %s too long to fit into target of width %d\n",
1115 for (
int i = 0; i < truth_labels.
size() && i < targets->
Width(); ++i) {
1118 for (
int i = truth_labels.
size(); i < targets->
Width(); ++i) {
1139 double char_error,
double word_error) {
1159 double total_error = 0.0;
1160 int width = deltas.
Width();
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;
1169 return sqrt(total_error / (width * num_classes));
1179 int width = deltas.
Width();
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]);
1187 if (0.5 <= abs_delta)
1191 return static_cast<double>(num_errors) / width;
1200 for (
int i = 0; i < truth_str.
size(); ++i) {
1202 ++label_counts[truth_str[i]];
1206 for (
int i = 0; i < ocr_str.
size(); ++i) {
1208 --label_counts[ocr_str[i]];
1211 int char_errors = 0;
1212 for (
int i = 0; i < label_counts.
size(); ++i) {
1213 char_errors += abs(label_counts[i]);
1215 if (truth_size == 0) {
1216 return (char_errors == 0) ? 0.0 : 1.0;
1218 return static_cast<double>(char_errors) / truth_size;
1224 using StrMap = std::unordered_map<std::string, int, std::hash<std::string>>;
1226 truth_str->
split(
' ', &truth_words);
1227 if (truth_words.
empty())
return 0.0;
1228 ocr_str->
split(
' ', &ocr_words);
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));
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));
1246 int word_recall_errs = 0;
1247 for (StrMap::const_iterator it = word_counts.begin(); it != word_counts.end();
1249 if (it->second > 0) word_recall_errs += it->second;
1251 return static_cast<double>(word_recall_errs) / truth_words.
size();
1261 double buffer_sum = 0.0;
1263 double mean = buffer_sum / mean_count;
1277 tprintf(
"Mean rms=%g%%, delta=%g%%, train=%g%%(%g%%), skip ratio=%g%%\n",
1325 double two_percent_more = error_rate + 2.0;
1332 tprintf(
"2 Percent improvement time=%d, best error was %g @ %d\n",
1337 if (tester !=
nullptr) {
int32_t improvement_steps_
LossType OutputLossType() const
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
void ScaleLearningRate(double factor)
void UpdateErrorBuffer(double new_error, ErrorTypes type)
LIST search(LIST list, void *key, int_compare is_equal)
DLLSYM void tprintf(const char *format,...)
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
void split(char c, GenericVector< STRING > *splited)
const int kNumAdjustmentIterations
const double kMinDivergenceRate
bool(*)(const GenericVector< char > &, const STRING &) FileWriter
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
const STRING & imagefilename() const
std::string VersionString() const
void OpenWrite(GenericVector< char > *data)
int ReduceLayerLearningRates(double factor, int num_samples, LSTMTrainer *samples_trainer)
static void NormalizeProbs(NetworkIO *probs)
void init_to_size(int size, const T &t)
bool MaintainCheckpoints(TestCallback tester, STRING *log_msg)
virtual STRING spec() const
const int kErrorGraphInterval
void FillErrorBuffer(double new_error, ErrorTypes type)
void StartSubtrainer(STRING *log_msg)
int training_iteration() const
static constexpr float kMinCertainty
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
bool GetComponent(TessdataType type, TFile *fp)
bool TransitionTrainingStage(float error_threshold)
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
bool SaveFile(const STRING &filename, FileWriter writer) const
void SetActivations(int t, int label, float ok_score)
const int kNumPagesPerBatch
bool SaveTraineddata(const STRING &filename)
LSTMTrainer * sub_trainer_
void ScaleLayerLearningRate(const STRING &id, double factor)
const STRING & name() const
SVEvent * AwaitEvent(SVEventType type)
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 ComputeRMSError(const NetworkIO &deltas)
const UNICHARSET & GetUnicharset() const
int prev_sample_iteration_
const int kMinStartedErrorRate
bool Open(const STRING &filename, FileReader reader)
CheckPointReader checkpoint_reader_
const char * c_str() const
double ComputeErrorRates(const NetworkIO &deltas, double char_error, double word_error)
void ExtractBestPathAsLabels(GenericVector< int > *labels, GenericVector< int > *xcoords) const
GenericVector< int > best_error_iterations_
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
STRING UpdateErrorGraph(int iteration, double error_rate, const GenericVector< char > &model_data, TestCallback tester)
void OverwriteEntry(TessdataType type, const char *data, int size)
GenericVector< char > worst_model_data_
float GetLayerLearningRate(const STRING &id) const
const char * string() const
bool LoadCharsets(const TessdataManager *mgr)
const double kSubTrainerMarginFraction
bool ReadLocalTrainingDump(const TessdataManager *mgr, const char *data, int size)
double best_error_rates_[ET_COUNT]
void DisplayForward(const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
GenericVector< double > best_error_history_
bool ComputeTextTargets(const NetworkIO &outputs, const GenericVector< int > &truth_labels, NetworkIO *targets)
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)
double error_rates_[ET_COUNT]
SubTrainerResult UpdateSubtrainer(STRING *log_msg)
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)
double NewSingleError(ErrorTypes type) const
virtual void DebugWeights()=0
bool LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)
virtual void Update(float learning_rate, float momentum, float adam_beta, int num_samples)
virtual void CountAlternators(const Network &other, double *same, double *changed) const
void DisplayTargets(const NetworkIO &targets, const char *window_name, ScrollView **window)
constexpr size_t countof(T const (&)[N]) noexcept
int checkpoint_iteration_
bool TestFlag(NetworkFlags flag) const
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
bool Serialize(SerializeAmount serialize_amount, const TessdataManager *mgr, TFile *fp) const
int sample_iteration() const
virtual StaticShape OutputShape(const StaticShape &input_shape) const
bool Init(const char *data_file_name)
STRING DecodeLabels(const GenericVector< int > &labels)
bool DeSerialize(bool swap, FILE *fp)
const double kStageTransitionThreshold
int32_t training_iteration_
bool(*)(const STRING &, GenericVector< char > *) FileReader
bool DeSerialize(char *data, size_t count=1)
double worst_error_rates_[ET_COUNT]
static bool InitNetwork(int num_outputs, STRING network_spec, int append_index, int net_flags, float weight_range, TRand *randomizer, Network **network)
virtual R Run(A1, A2, A3, A4)=0
bool EncodeString(const STRING &str, GenericVector< int > *labels) const
void DebugActivationPath(const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
int learning_iteration() const
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
void SaveRecognitionDump(GenericVector< char > *data) const
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
static const int kRollingBufferSize_
bool has_special_codes() const
Network * GetLayer(const STRING &id) const
CheckPointWriter checkpoint_writer_
const double kLearningRateDecay
bool Serialize(const TessdataManager *mgr, TFile *fp) const
void add_str_int(const char *str, int number)
const GenericVector< TBOX > & boxes() const
const int kMinStallIterations
void PrepareLogMsg(STRING *log_msg) const
bool Serialize(const char *data, size_t count=1)
bool ComputeCTCTargets(const GenericVector< int > &truth_labels, NetworkIO *outputs, NetworkIO *targets)
GenericVector< char > best_model_data_
double ComputeWinnerError(const NetworkIO &deltas)
bool SimpleTextOutput() const
void SetVersionString(const std::string &v_str)
float error_rate_of_last_saved_best_
std::vector< int > MapRecoder(const UNICHARSET &old_chset, const UnicharCompress &old_recoder) const
double learning_rate() const
const double kImprovementFraction
void LogIterations(const char *intro_str, STRING *log_msg) const
STRING DumpFilename() const
_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)
const double kBestCheckpointFraction
double SignedRand(double range)
GenericVector< STRING > EnumerateLayers() const
const STRING & transcription() const
int32_t sample_iteration_
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
DocumentCache training_data_
double ComputeWordError(STRING *truth_str, STRING *ocr_str)
void ReduceLearningRates(LSTMTrainer *samples_trainer, STRING *log_msg)
void Decode(const NetworkIO &output, double dict_ratio, double cert_offset, double worst_dict_cert, const UNICHARSET *charset, int lstm_choice_mode=0)
const double kHighConfidence
virtual StaticShape InputShape() const
int last_perfect_training_iteration_
const STRING & language() const
int CurrentTrainingStage() const
static std::string CleanupString(const char *utf8_str)
bool LoadAllTrainingData(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, bool randomly_rotate)
GenericVector< char > best_trainer_
bool TryLoadingCheckpoint(const char *filename, const char *old_traineddata)
virtual void SetEnableTraining(TrainingState state)
virtual R Run(A1, A2, A3)=0
bool encode_string(const char *str, bool give_up_on_failure, GenericVector< UNICHAR_ID > *encoding, GenericVector< char > *lengths, int *encoded_length) const
void SetIteration(int iteration)
bool DeSerialize(TFile *fp)
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const
void SubtractAllFromFloat(const NetworkIO &src)
NetworkScratch scratch_space_
bool Serialize(FILE *fp) const
const GENERIC_2D_ARRAY< float > & float_array() const
void add_str_double(const char *str, double number)
void Resize(const NetworkIO &src, int num_features)
int InitTensorFlowNetwork(const std::string &tf_proto)
int IntCastRounded(double x)
virtual int RemapOutputs(int old_no, const std::vector< int > &code_map)
bool load_from_file(const char *const filename, bool skip_fragments)
static bool ComputeCTCTargets(const GenericVector< int > &truth_labels, int null_char, const GENERIC_2D_ARRAY< float > &outputs, NetworkIO *targets)
bool InitNetwork(const STRING &network_spec, int append_index, int net_flags, float weight_range, float learning_rate, float momentum, float adam_beta)
GenericVector< double > error_buffers_[ET_COUNT]
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)=0
bool AnySuspiciousTruth(float confidence_thr) const