21 #include "config_auto.h" 27 #include "allheaders.h" 35 #ifdef INCLUDE_TENSORFLOW 74 : randomly_rotate_(false),
82 sub_trainer_(nullptr) {
90 const char* model_base,
const char* checkpoint_name,
91 int debug_interval, int64_t max_memory)
92 : randomly_rotate_(false),
93 training_data_(max_memory),
94 file_reader_(file_reader),
95 file_writer_(file_writer),
96 checkpoint_reader_(checkpoint_reader),
97 checkpoint_writer_(checkpoint_writer),
98 sub_trainer_(nullptr),
129 const char* old_traineddata) {
132 tprintf(
"Loaded file %s, unpacking...\n", filename);
135 if (((old_traineddata ==
nullptr || *old_traineddata ==
'\0') &&
137 filename == old_traineddata) {
142 if (old_traineddata ==
nullptr || *old_traineddata ==
'\0') {
143 tprintf(
"Must supply the old traineddata for code conversion!\n");
155 std::vector<int> code_map =
MapRecoder(old_chset, old_recoder);
172 int net_flags,
float weight_range,
173 float learning_rate,
float momentum,
181 append_index, net_flags, weight_range,
186 tprintf(
"Built network:%s from request %s\n",
189 "Training parameters:\n Debug interval = %d," 190 " weights = %g, learning rate = %g, momentum=%g\n",
199 #ifdef INCLUDE_TENSORFLOW 201 TFNetwork* tf_net =
new TFNetwork(
"TensorFlow");
204 tprintf(
"InitFromProtoStr failed!!\n");
211 tprintf(
"TensorFlow not compiled in! -DINCLUDE_TENSORFLOW\n");
231 for (
int i = 0; i <
ET_COUNT; ++i) {
244 const ImageData* trainingdata,
int iteration,
double min_dict_ratio,
245 double dict_ratio_step,
double max_dict_ratio,
double min_cert_offset,
246 double cert_offset_step,
double max_cert_offset,
STRING* results) {
268 for (
double r = min_dict_ratio; r < max_dict_ratio; r += dict_ratio_step) {
269 for (
double c = min_cert_offset; c < max_cert_offset;
270 c += cert_offset_step) {
272 search.ExtractBestPathAsLabels(&ocr_labels, &xcoords);
277 if ((r == min_dict_ratio && c == min_cert_offset) ||
278 !std::isfinite(word_error)) {
281 tprintf(
"r=%g, c=%g, truth=%s, ocr=%s, wderr=%g, truth[0]=%d\n", r, c,
302 bool randomly_rotate) {
338 *log_msg +=
UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
351 *log_msg +=
" failed to write best model:";
353 *log_msg +=
" wrote best model:";
356 *log_msg += best_model_name;
361 *log_msg +=
UpdateErrorGraph(iteration, error_rate, rec_model_data, tester);
365 *log_msg +=
"\nDivergence! ";
382 result = sub_trainer_result !=
STR_NONE;
390 *log_msg +=
" failed to write checkpoint.";
392 *log_msg +=
" wrote checkpoint.";
413 *log_msg += intro_str;
438 for (
int i = 0; i <
ET_COUNT; ++i) {
443 uint8_t amount = serialize_amount;
444 if (!fp->
Serialize(&amount))
return false;
445 if (serialize_amount ==
LIGHT)
return true;
460 if (!sub_data.
Serialize(fp))
return false;
474 tprintf(
"Warning: LSTMTrainer deserialized an LSTMRecognizer!\n");
482 for (
int i = 0; i <
ET_COUNT; ++i) {
489 if (amount ==
LIGHT)
return true;
503 if (sub_data.
empty()) {
521 *log_msg +=
" Failed to revert to previous best for trial!";
525 log_msg->
add_str_int(
" Trial sub_trainer_ from iteration ",
550 double sub_margin = (training_error - sub_error) / sub_error;
559 int target_iteration =
564 STRING batch_log =
"Sub:";
568 *log_msg += batch_log;
570 sub_margin = (training_error - sub_error) / sub_error;
578 log_msg->
add_str_int(
" Sub trainer wins at iteration ",
595 log_msg->
add_str_int(
"\nReduced learning rate on layers: ", num_reduced);
617 int num_layers = layers.
size();
622 for (
int i = 0; i < LR_COUNT; ++i) {
626 double momentum_factor = 1.0 / (1.0 -
momentum_);
629 for (
int i = 0; i < num_layers; ++i) {
634 for (
int s = 0; s < num_samples; ++s) {
636 for (
int ww = 0; ww < LR_COUNT; ++ww) {
638 float ww_factor = momentum_factor;
639 if (ww == LR_DOWN) ww_factor *= factor;
646 for (
int i = 0; i < num_layers; ++i) {
647 if (num_weights[i] == 0)
continue;
655 if (trainingdata ==
nullptr)
continue;
659 for (
int i = 0; i < num_layers; ++i) {
660 if (num_weights[i] == 0)
continue;
668 layer->
Update(0.0, 0.0, 0.0, 0);
672 float before_bad = bad_sums[ww][i];
673 float before_ok = ok_sums[ww][i];
675 &ok_sums[ww][i], &bad_sums[ww][i]);
677 bad_sums[ww][i] + ok_sums[ww][i] - before_bad - before_ok;
679 bad_frac = (bad_sums[ww][i] - before_bad) / bad_frac;
685 for (
int i = 0; i < num_layers; ++i) {
686 if (num_weights[i] == 0)
continue;
689 double total_down = bad_sums[LR_DOWN][i] + ok_sums[LR_DOWN][i];
690 double total_same = bad_sums[LR_SAME][i] + ok_sums[LR_SAME][i];
691 double frac_down = bad_sums[LR_DOWN][i] / total_down;
692 double frac_same = bad_sums[LR_SAME][i] / total_same;
694 lr * factor, 100.0 * frac_down, lr, 100.0 * frac_same);
703 if (num_lowered == 0) {
705 for (
int i = 0; i < num_layers; ++i) {
706 if (num_weights[i] > 0) {
722 tprintf(
"Empty truth string!\n");
730 if (unicharset.
encode_string(cleaned.c_str(),
true, &internal_labels,
nullptr,
733 for (
int i = 0; i < internal_labels.
size(); ++i) {
734 if (recoder !=
nullptr) {
739 for (
int j = 0; j < len; ++j) {
753 if (success)
return true;
755 tprintf(
"Encoding of string failed! Failure bytes:");
756 while (err_index < cleaned.size()) {
757 tprintf(
" %x", cleaned[err_index++]);
786 #ifndef GRAPHICS_DISABLED 790 #endif // GRAPHICS_DISABLED 801 if (trainingdata ==
nullptr) {
802 tprintf(
"Null trainingdata.\n");
810 tprintf(
"Can't encode transcription: '%s' in language '%s'\n",
815 bool upside_down =
false;
825 for (
int c = 0; c < truth_labels.
size(); ++c) {
833 while (w < truth_labels.
size() &&
836 if (w == truth_labels.
size()) {
837 tprintf(
"Blank transcription: %s\n",
844 if (!
RecognizeLine(*trainingdata, invert, debug, invert, upside_down,
845 &image_scale, &inputs, fwd_outputs)) {
846 tprintf(
"Image not trainable\n");
853 tprintf(
"Compute simple targets failed!\n");
856 }
else if (loss_type ==
LT_CTC) {
858 tprintf(
"Compute CTC targets failed!\n");
862 tprintf(
"Logistic outputs not implemented yet!\n");
869 if (loss_type !=
LT_CTC) {
889 trainingdata->
page_number(), delta_error == 0.0 ?
"(Perfect)" :
"");
891 if (delta_error == 0.0)
return PERFECT;
910 const char* data,
int size) {
912 tprintf(
"Warning: data size is 0 in LSTMTrainer::ReadLocalTrainingDump\n");
925 recognizer_data.
size());
944 filename +=
".checkpoint";
961 std::vector<int> code_map(num_new_codes, -1);
962 for (
int c = 0; c < num_new_codes; ++c) {
966 for (
int uid = 0; uid <= num_new_unichars; ++uid) {
970 while (code_index < length && codes(code_index) != c) ++code_index;
971 if (code_index == length)
continue;
974 uid < num_new_unichars
976 : old_chset.
size() - 1;
977 if (old_uid == INVALID_UNICHAR_ID)
continue;
980 if (code_index < old_recoder.
EncodeUnichar(old_uid, &old_codes)) {
981 old_code = old_codes(code_index);
985 code_map[c] = old_code;
998 "Must provide a traineddata containing lstm_unicharset and" 999 " lstm_recoder!\n" !=
nullptr);
1035 if (truth_text.
string() ==
nullptr || truth_text.
length() <= 0) {
1036 tprintf(
"Empty truth string at decode time!\n");
1045 tprintf(
"Iteration %d: ALIGNED TRUTH : %s\n",
1048 tprintf(
"TRAINING activation path for truth string %s\n",
1063 const char* window_name,
ScrollView** window) {
1064 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics. 1065 int width = targets.
Width();
1069 for (
int c = 0; c < num_features; ++c) {
1071 (*window)->Pen(static_cast<ScrollView::Color>(color));
1073 for (
int t = 0; t < width; ++t) {
1074 double target = targets.
f(t)[c];
1078 (*window)->SetCursor(t - 1, 0);
1081 (*window)->DrawTo(t, target);
1082 }
else if (start_t >= 0) {
1083 (*window)->DrawTo(t, 0);
1084 (*window)->DrawTo(start_t - 1, 0);
1089 (*window)->DrawTo(width, 0);
1090 (*window)->DrawTo(start_t - 1, 0);
1093 (*window)->Update();
1094 #endif // GRAPHICS_DISABLED 1102 if (truth_labels.
size() > targets->
Width()) {
1103 tprintf(
"Error: transcription %s too long to fit into target of width %d\n",
1107 for (
int i = 0; i < truth_labels.
size() && i < targets->
Width(); ++i) {
1110 for (
int i = truth_labels.
size(); i < targets->
Width(); ++i) {
1131 double char_error,
double word_error) {
1151 double total_error = 0.0;
1152 int width = deltas.
Width();
1154 for (
int t = 0; t < width; ++t) {
1155 const float* class_errs = deltas.
f(t);
1156 for (
int c = 0; c < num_classes; ++c) {
1157 double error = class_errs[c];
1158 total_error += error * error;
1161 return sqrt(total_error / (width * num_classes));
1171 int width = deltas.
Width();
1173 for (
int t = 0; t < width; ++t) {
1174 const float* class_errs = deltas.
f(t);
1175 for (
int c = 0; c < num_classes; ++c) {
1176 float abs_delta = fabs(class_errs[c]);
1179 if (0.5 <= abs_delta)
1183 return static_cast<double>(num_errors) / width;
1192 for (
int i = 0; i < truth_str.
size(); ++i) {
1194 ++label_counts[truth_str[i]];
1198 for (
int i = 0; i < ocr_str.
size(); ++i) {
1200 --label_counts[ocr_str[i]];
1203 int char_errors = 0;
1204 for (
int i = 0; i < label_counts.
size(); ++i) {
1205 char_errors += abs(label_counts[i]);
1207 if (truth_size == 0) {
1208 return (char_errors == 0) ? 0.0 : 1.0;
1210 return static_cast<double>(char_errors) / truth_size;
1216 using StrMap = std::unordered_map<std::string, int, std::hash<std::string>>;
1218 truth_str->
split(
' ', &truth_words);
1219 if (truth_words.
empty())
return 0.0;
1220 ocr_str->
split(
' ', &ocr_words);
1222 for (
int i = 0; i < truth_words.
size(); ++i) {
1223 std::string truth_word(truth_words[i].
string());
1224 StrMap::iterator it = word_counts.find(truth_word);
1225 if (it == word_counts.end())
1226 word_counts.insert(std::make_pair(truth_word, 1));
1230 for (
int i = 0; i < ocr_words.
size(); ++i) {
1231 std::string ocr_word(ocr_words[i].
string());
1232 StrMap::iterator it = word_counts.find(ocr_word);
1233 if (it == word_counts.end())
1234 word_counts.insert(std::make_pair(ocr_word, -1));
1238 int word_recall_errs = 0;
1239 for (StrMap::const_iterator it = word_counts.begin(); it != word_counts.end();
1241 if (it->second > 0) word_recall_errs += it->second;
1243 return static_cast<double>(word_recall_errs) / truth_words.
size();
1253 double buffer_sum = 0.0;
1254 for (
int i = 0; i < mean_count; ++i) buffer_sum +=
error_buffers_[type][i];
1255 double mean = buffer_sum / mean_count;
1269 tprintf(
"Mean rms=%g%%, delta=%g%%, train=%g%%(%g%%), skip ratio=%g%%\n",
1317 double two_percent_more = error_rate + 2.0;
1324 tprintf(
"2 Percent improvement time=%d, best error was %g @ %d\n",
1329 if (tester !=
nullptr) {
const UNICHARSET & GetUnicharset() const
void ExtractBestPathAsLabels(GenericVector< int > *labels, GenericVector< int > *xcoords) const
Network * GetLayer(const STRING &id) const
DocumentCache training_data_
bool InitNetwork(const STRING &network_spec, int append_index, int net_flags, float weight_range, float learning_rate, float momentum, float adam_beta)
bool LoadCharsets(const TessdataManager *mgr)
bool TransitionTrainingStage(float error_threshold)
STRING UpdateErrorGraph(int iteration, double error_rate, const GenericVector< char > &model_data, TestCallback tester)
const GenericVector< TBOX > & boxes() const
void SetVersionString(const std::string &v_str)
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const
virtual void CountAlternators(const Network &other, double *same, double *changed) const
bool encode_string(const char *str, bool give_up_on_failure, GenericVector< UNICHAR_ID > *encoding, GenericVector< char > *lengths, int *encoded_length) const
bool GetComponent(TessdataType type, TFile *fp)
void ScaleLayerLearningRate(const STRING &id, double factor)
double worst_error_rates_[ET_COUNT]
void OpenWrite(GenericVector< char > *data)
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
void SetActivations(int t, int label, float ok_score)
const int kMinStartedErrorRate
bool Serialize(SerializeAmount serialize_amount, const TessdataManager *mgr, TFile *fp) const
void Decode(const NetworkIO &output, double dict_ratio, double cert_offset, double worst_dict_cert, const UNICHARSET *charset, int lstm_choice_mode=0)
static void NormalizeProbs(NetworkIO *probs)
const double kHighConfidence
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
void OverwriteEntry(TessdataType type, const char *data, int size)
bool SaveTraineddata(const STRING &filename)
int learning_iteration() const
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
const char * string() const
virtual R Run(A1, A2, A3, A4)=0
STRING DecodeLabels(const GenericVector< int > &labels)
const double kMinDivergenceRate
virtual STRING spec() const
bool DeSerialize(char *data, size_t count=1)
static const int kRollingBufferSize_
const STRING & language() const
bool ReadLocalTrainingDump(const TessdataManager *mgr, const char *data, int size)
LSTMTrainer * sub_trainer_
int InitTensorFlowNetwork(const std::string &tf_proto)
void SetIteration(int iteration)
int training_iteration() const
bool MaintainCheckpoints(TestCallback tester, STRING *log_msg)
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
bool SimpleTextOutput() const
int ReduceLayerLearningRates(double factor, int num_samples, LSTMTrainer *samples_trainer)
bool DeSerialize(bool swap, FILE *fp)
bool DebugLSTMTraining(const NetworkIO &inputs, const ImageData &trainingdata, const NetworkIO &fwd_outputs, const GenericVector< int > &truth_labels, const NetworkIO &outputs)
void ScaleLearningRate(double factor)
static bool ComputeCTCTargets(const GenericVector< int > &truth_labels, int null_char, const GENERIC_2D_ARRAY< float > &outputs, NetworkIO *targets)
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
const STRING & imagefilename() const
double best_error_rates_[ET_COUNT]
bool Serialize(FILE *fp) const
void SubtractAllFromFloat(const NetworkIO &src)
NetworkScratch scratch_space_
int prev_sample_iteration_
constexpr size_t countof(T const (&)[N]) noexcept
int CurrentTrainingStage() const
double ComputeWordError(STRING *truth_str, STRING *ocr_str)
void UpdateErrorBuffer(double new_error, ErrorTypes type)
float GetLayerLearningRate(const STRING &id) const
int sample_iteration() const
void PrepareLogMsg(STRING *log_msg) const
void ReduceLearningRates(LSTMTrainer *samples_trainer, STRING *log_msg)
void Resize(const NetworkIO &src, int num_features)
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
void split(const char c, GenericVector< STRING > *splited)
GenericVector< char > best_trainer_
virtual void SetEnableTraining(TrainingState state)
bool ComputeCTCTargets(const GenericVector< int > &truth_labels, NetworkIO *outputs, NetworkIO *targets)
double ComputeWinnerError(const NetworkIO &deltas)
virtual StaticShape InputShape() const
GenericVector< double > best_error_history_
void SaveRecognitionDump(GenericVector< char > *data) const
Trainability GridSearchDictParams(const ImageData *trainingdata, int iteration, double min_dict_ratio, double dict_ratio_step, double max_dict_ratio, double min_cert_offset, double cert_offset_step, double max_cert_offset, STRING *results)
void DebugActivationPath(const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
const double kImprovementFraction
SVEvent * AwaitEvent(SVEventType type)
void FillErrorBuffer(double new_error, ErrorTypes type)
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
void DisplayForward(const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
void init_to_size(int size, const T &t)
void add_str_double(const char *str, double number)
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
const STRING & transcription() const
bool Init(const char *data_file_name)
int IntCastRounded(double x)
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
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)
GenericVector< int > best_error_iterations_
void LogIterations(const char *intro_str, STRING *log_msg) const
int32_t improvement_steps_
LIST search(LIST list, void *key, int_compare is_equal)
const STRING & name() const
bool Serialize(const char *data, size_t count=1)
DLLSYM void tprintf(const char *format,...)
bool TryLoadingCheckpoint(const char *filename, const char *old_traineddata)
double ComputeErrorRates(const NetworkIO &deltas, double char_error, double word_error)
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
void StartSubtrainer(STRING *log_msg)
static std::string CleanupString(const char *utf8_str)
double NewSingleError(ErrorTypes type) const
SubTrainerResult UpdateSubtrainer(STRING *log_msg)
GenericVector< char > best_model_data_
virtual StaticShape OutputShape(const StaticShape &input_shape) const
bool Open(const STRING &filename, FileReader reader)
const double kLearningRateDecay
void add_str_int(const char *str, int number)
STRING DumpFilename() const
int checkpoint_iteration_
bool EncodeString(const STRING &str, GenericVector< int > *labels) const
LossType OutputLossType() const
const int kMinStallIterations
bool LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)
static const float kMinCertainty
bool ComputeTextTargets(const NetworkIO &outputs, const GenericVector< int > &truth_labels, NetworkIO *targets)
float error_rate_of_last_saved_best_
double learning_rate() const
static bool InitNetwork(int num_outputs, STRING network_spec, int append_index, int net_flags, float weight_range, TRand *randomizer, Network **network)
GenericVector< STRING > EnumerateLayers() const
double SignedRand(double range)
const double kSubTrainerMarginFraction
const int kNumPagesPerBatch
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
bool SaveFile(const STRING &filename, FileWriter writer) const
const double kStageTransitionThreshold
bool DeSerialize(TFile *fp)
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
std::string VersionString() const
int32_t sample_iteration_
int32_t training_iteration_
virtual void Update(float learning_rate, float momentum, float adam_beta, int num_samples)
bool has_special_codes() const
bool TestFlag(NetworkFlags flag) const
std::vector< int > MapRecoder(const UNICHARSET &old_chset, const UnicharCompress &old_recoder) const
GenericVector< char > worst_model_data_
int last_perfect_training_iteration_
virtual void DebugWeights()
bool LoadAllTrainingData(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, bool randomly_rotate)
GenericVector< double > error_buffers_[ET_COUNT]
bool load_from_file(const char *const filename, bool skip_fragments)
bool Serialize(const TessdataManager *mgr, TFile *fp) const
CheckPointReader checkpoint_reader_
const int kNumAdjustmentIterations
double ComputeRMSError(const NetworkIO &deltas)
virtual R Run(A1, A2, A3)=0
bool(* FileWriter)(const GenericVector< char > &data, const STRING &filename)
virtual int RemapOutputs(int old_no, const std::vector< int > &code_map)
bool AnySuspiciousTruth(float confidence_thr) const
double ComputeCharError(const GenericVector< int > &truth_str, const GenericVector< int > &ocr_str)
void DisplayTargets(const NetworkIO &targets, const char *window_name, ScrollView **window)
const int kErrorGraphInterval
const GENERIC_2D_ARRAY< float > & float_array() const
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)
CheckPointWriter checkpoint_writer_
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
double error_rates_[ET_COUNT]
const double kBestCheckpointFraction