21 #include "config_auto.h" 27 #include "allheaders.h" 35 #ifdef INCLUDE_TENSORFLOW 74 : randomly_rotate_(false),
90 const char* model_base,
const char* checkpoint_name,
91 int debug_interval,
inT64 max_memory)
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,
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) {
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;
443 for (
int i = 0; i <
ET_COUNT; ++i) {
449 uinT8 amount = serialize_amount;
450 if (fp->
FWrite(&amount,
sizeof(amount), 1) != 1)
return false;
451 if (serialize_amount ==
LIGHT)
return true;
473 if (!sub_data.
Serialize(fp))
return false;
489 tprintf(
"Warning: LSTMTrainer deserialized an LSTMRecognizer!\n");
502 for (
int i = 0; i <
ET_COUNT; ++i) {
509 if (fp->
FRead(&amount,
sizeof(amount), 1) != 1)
return false;
510 if (amount ==
LIGHT)
return true;
531 if (sub_data.
empty()) {
551 *log_msg +=
" Failed to revert to previous best for trial!";
555 log_msg->
add_str_int(
" Trial sub_trainer_ from iteration ",
580 double sub_margin = (training_error - sub_error) / sub_error;
581 if (sub_margin >= kSubTrainerMarginFraction) {
589 int target_iteration =
594 STRING batch_log =
"Sub:";
598 *log_msg += batch_log;
600 sub_margin = (training_error - sub_error) / sub_error;
603 sub_margin >= kSubTrainerMarginFraction) {
608 log_msg->
add_str_int(
" Sub trainer wins at iteration ",
624 kLearningRateDecay, kNumAdjustmentIterations, samples_trainer);
625 log_msg->
add_str_int(
"\nReduced learning rate on layers: ", num_reduced);
647 int num_layers = layers.
size();
652 for (
int i = 0; i < LR_COUNT; ++i) {
656 double momentum_factor = 1.0 / (1.0 -
momentum_);
659 for (
int i = 0; i < num_layers; ++i) {
664 for (
int s = 0; s < num_samples; ++s) {
666 for (
int ww = 0; ww < LR_COUNT; ++ww) {
668 float ww_factor = momentum_factor;
669 if (ww == LR_DOWN) ww_factor *= factor;
676 for (
int i = 0; i < num_layers; ++i) {
677 if (num_weights[i] == 0)
continue;
685 if (trainingdata == NULL)
continue;
689 for (
int i = 0; i < num_layers; ++i) {
690 if (num_weights[i] == 0)
continue;
698 layer->
Update(0.0, 0.0, 0.0, 0);
702 float before_bad = bad_sums[ww][i];
703 float before_ok = ok_sums[ww][i];
705 &ok_sums[ww][i], &bad_sums[ww][i]);
707 bad_sums[ww][i] + ok_sums[ww][i] - before_bad - before_ok;
709 bad_frac = (bad_sums[ww][i] - before_bad) / bad_frac;
715 for (
int i = 0; i < num_layers; ++i) {
716 if (num_weights[i] == 0)
continue;
719 double total_down = bad_sums[LR_DOWN][i] + ok_sums[LR_DOWN][i];
720 double total_same = bad_sums[LR_SAME][i] + ok_sums[LR_SAME][i];
721 double frac_down = bad_sums[LR_DOWN][i] / total_down;
722 double frac_same = bad_sums[LR_SAME][i] / total_same;
724 lr * factor, 100.0 * frac_down, lr, 100.0 * frac_same);
725 if (frac_down < frac_same * kImprovementFraction) {
733 if (num_lowered == 0) {
735 for (
int i = 0; i < num_layers; ++i) {
736 if (num_weights[i] > 0) {
752 tprintf(
"Empty truth string!\n");
758 if (!simple_text) labels->
push_back(null_char);
760 if (unicharset.
encode_string(cleaned.c_str(),
true, &internal_labels, NULL,
763 for (
int i = 0; i < internal_labels.
size(); ++i) {
764 if (recoder != NULL) {
769 for (
int j = 0; j < len; ++j) {
771 if (!simple_text) labels->
push_back(null_char);
780 if (!simple_text) labels->
push_back(null_char);
783 if (success)
return true;
785 tprintf(
"Encoding of string failed! Failure bytes:");
786 while (err_index < cleaned.size()) {
787 tprintf(
" %x", cleaned[err_index++]);
816 #ifndef GRAPHICS_DISABLED 820 #endif // GRAPHICS_DISABLED 831 if (trainingdata == NULL) {
832 tprintf(
"Null trainingdata.\n");
840 tprintf(
"Can't encode transcription: '%s' in language '%s'\n",
845 bool upside_down =
false;
855 for (
int c = 0; c < truth_labels.
size(); ++c) {
863 while (w < truth_labels.
size() &&
866 if (w == truth_labels.
size()) {
867 tprintf(
"Blank transcription: %s\n",
874 if (!
RecognizeLine(*trainingdata, invert, debug, invert, upside_down,
875 &image_scale, &inputs, fwd_outputs)) {
876 tprintf(
"Image not trainable\n");
883 tprintf(
"Compute simple targets failed!\n");
886 }
else if (loss_type ==
LT_CTC) {
888 tprintf(
"Compute CTC targets failed!\n");
892 tprintf(
"Logistic outputs not implemented yet!\n");
899 if (loss_type !=
LT_CTC) {
919 trainingdata->
page_number(), delta_error == 0.0 ?
"(Perfect)" :
"");
921 if (delta_error == 0.0)
return PERFECT;
940 const char* data,
int size) {
942 tprintf(
"Warning: data size is 0 in LSTMTrainer::ReadLocalTrainingDump\n");
955 recognizer_data.
size());
974 filename +=
".checkpoint";
991 std::vector<int> code_map(num_new_codes, -1);
992 for (
int c = 0; c < num_new_codes; ++c) {
996 for (
int uid = 0; uid <= num_new_unichars; ++uid) {
1000 while (code_index < length && codes(code_index) != c) ++code_index;
1001 if (code_index == length)
continue;
1004 uid < num_new_unichars
1006 : old_chset.
size() - 1;
1007 if (old_uid == INVALID_UNICHAR_ID)
continue;
1010 if (code_index < old_recoder.
EncodeUnichar(old_uid, &old_codes)) {
1011 old_code = old_codes(code_index);
1015 code_map[c] = old_code;
1028 "Must provide a traineddata containing lstm_unicharset and" 1029 " lstm_recoder!\n" !=
nullptr);
1065 if (truth_text.
string() == NULL || truth_text.
length() <= 0) {
1066 tprintf(
"Empty truth string at decode time!\n");
1075 tprintf(
"Iteration %d: ALIGNED TRUTH : %s\n",
1078 tprintf(
"TRAINING activation path for truth string %s\n",
1093 const char* window_name,
ScrollView** window) {
1094 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics. 1095 int width = targets.
Width();
1099 for (
int c = 0; c < num_features; ++c) {
1101 (*window)->Pen(static_cast<ScrollView::Color>(color));
1103 for (
int t = 0; t < width; ++t) {
1104 double target = targets.
f(t)[c];
1108 (*window)->SetCursor(t - 1, 0);
1111 (*window)->DrawTo(t, target);
1112 }
else if (start_t >= 0) {
1113 (*window)->DrawTo(t, 0);
1114 (*window)->DrawTo(start_t - 1, 0);
1119 (*window)->DrawTo(width, 0);
1120 (*window)->DrawTo(start_t - 1, 0);
1123 (*window)->Update();
1124 #endif // GRAPHICS_DISABLED 1132 if (truth_labels.
size() > targets->
Width()) {
1133 tprintf(
"Error: transcription %s too long to fit into target of width %d\n",
1137 for (
int i = 0; i < truth_labels.
size() && i < targets->
Width(); ++i) {
1140 for (
int i = truth_labels.
size(); i < targets->
Width(); ++i) {
1161 double char_error,
double word_error) {
1181 double total_error = 0.0;
1182 int width = deltas.
Width();
1184 for (
int t = 0; t < width; ++t) {
1185 const float* class_errs = deltas.
f(t);
1186 for (
int c = 0; c < num_classes; ++c) {
1187 double error = class_errs[c];
1188 total_error += error * error;
1191 return sqrt(total_error / (width * num_classes));
1201 int width = deltas.
Width();
1203 for (
int t = 0; t < width; ++t) {
1204 const float* class_errs = deltas.
f(t);
1205 for (
int c = 0; c < num_classes; ++c) {
1206 float abs_delta = fabs(class_errs[c]);
1209 if (0.5 <= abs_delta)
1213 return static_cast<double>(num_errors) / width;
1222 for (
int i = 0; i < truth_str.
size(); ++i) {
1224 ++label_counts[truth_str[i]];
1228 for (
int i = 0; i < ocr_str.
size(); ++i) {
1230 --label_counts[ocr_str[i]];
1233 int char_errors = 0;
1234 for (
int i = 0; i < label_counts.
size(); ++i) {
1235 char_errors += abs(label_counts[i]);
1237 if (truth_size == 0) {
1238 return (char_errors == 0) ? 0.0 : 1.0;
1240 return static_cast<double>(char_errors) / truth_size;
1246 typedef std::unordered_map<std::string, int, std::hash<std::string> > StrMap;
1248 truth_str->
split(
' ', &truth_words);
1249 if (truth_words.
empty())
return 0.0;
1250 ocr_str->
split(
' ', &ocr_words);
1252 for (
int i = 0; i < truth_words.
size(); ++i) {
1253 std::string truth_word(truth_words[i].
string());
1254 StrMap::iterator it = word_counts.find(truth_word);
1255 if (it == word_counts.end())
1256 word_counts.insert(std::make_pair(truth_word, 1));
1260 for (
int i = 0; i < ocr_words.
size(); ++i) {
1261 std::string ocr_word(ocr_words[i].
string());
1262 StrMap::iterator it = word_counts.find(ocr_word);
1263 if (it == word_counts.end())
1264 word_counts.insert(std::make_pair(ocr_word, -1));
1268 int word_recall_errs = 0;
1269 for (StrMap::const_iterator it = word_counts.begin(); it != word_counts.end();
1271 if (it->second > 0) word_recall_errs += it->second;
1273 return static_cast<double>(word_recall_errs) / truth_words.
size();
1283 double buffer_sum = 0.0;
1284 for (
int i = 0; i < mean_count; ++i) buffer_sum +=
error_buffers_[type][i];
1285 double mean = buffer_sum / mean_count;
1299 tprintf(
"Mean rms=%g%%, delta=%g%%, train=%g%%(%g%%), skip ratio=%g%%\n",
1347 double two_percent_more = error_rate + 2.0;
1354 tprintf(
"2 Percent improvement time=%d, best error was %g @ %d\n",
1359 if (tester != NULL) {
virtual STRING spec() const
int CurrentTrainingStage() const
void DisplayForward(const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
int FWrite(const void *buffer, int size, int count)
virtual void Update(float learning_rate, float momentum, float adam_beta, int num_samples)
static const int kRollingBufferSize_
bool SaveFile(const STRING &filename, FileWriter writer) const
void SetIteration(int iteration)
void Resize(const NetworkIO &src, int num_features)
const double kLearningRateDecay
double ComputeWordError(STRING *truth_str, STRING *ocr_str)
bool TryLoadingCheckpoint(const char *filename, const char *old_traineddata)
int last_perfect_training_iteration_
void DebugActivationPath(const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
GenericVector< char > best_trainer_
bool encode_string(const char *str, bool give_up_on_failure, GenericVector< UNICHAR_ID > *encoding, GenericVector< char > *lengths, int *encoded_length) const
void DisplayTargets(const NetworkIO &targets, const char *window_name, ScrollView **window)
GenericVector< double > best_error_history_
int InitTensorFlowNetwork(const std::string &tf_proto)
void FillErrorBuffer(double new_error, ErrorTypes type)
double learning_rate() const
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
double worst_error_rates_[ET_COUNT]
void OpenWrite(GenericVector< char > *data)
double ComputeRMSError(const NetworkIO &deltas)
const STRING & imagefilename() const
double ComputeErrorRates(const NetworkIO &deltas, double char_error, double word_error)
double ComputeCharError(const GenericVector< int > &truth_str, const GenericVector< int > &ocr_str)
double ComputeWinnerError(const NetworkIO &deltas)
void Decode(const NetworkIO &output, double dict_ratio, double cert_offset, double worst_dict_cert, const UNICHARSET *charset)
bool LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)
double best_error_rates_[ET_COUNT]
void add_str_int(const char *str, int number)
void SaveRecognitionDump(GenericVector< char > *data) const
void SubtractAllFromFloat(const NetworkIO &src)
GenericVector< char > worst_model_data_
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
const GENERIC_2D_ARRAY< float > & float_array() const
LSTMTrainer * sub_trainer_
bool ComputeCTCTargets(const GenericVector< int > &truth_labels, NetworkIO *outputs, NetworkIO *targets)
const int kMinStartedErrorRate
bool InitNetwork(const STRING &network_spec, int append_index, int net_flags, float weight_range, float learning_rate, float momentum, float adam_beta)
void LogIterations(const char *intro_str, STRING *log_msg) const
float error_rate_of_last_saved_best_
CheckPointReader checkpoint_reader_
bool TestFlag(NetworkFlags flag) const
SVEvent * AwaitEvent(SVEventType type)
Network * GetLayer(const STRING &id) const
void StartSubtrainer(STRING *log_msg)
bool Serialize(const TessdataManager *mgr, TFile *fp) const
bool ComputeTextTargets(const NetworkIO &outputs, const GenericVector< int > &truth_labels, NetworkIO *targets)
void ScaleLayerLearningRate(const STRING &id, double factor)
inT32 training_iteration_
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
static string CleanupString(const char *utf8_str)
int sample_iteration() const
const int kMinStallIterations
static void NormalizeProbs(NetworkIO *probs)
virtual void SetEnableTraining(TrainingState state)
bool EncodeString(const STRING &str, GenericVector< int > *labels) const
static bool InitNetwork(int num_outputs, STRING network_spec, int append_index, int net_flags, float weight_range, TRand *randomizer, Network **network)
bool GetComponent(TessdataType type, TFile *fp)
virtual void CountAlternators(const Network &other, double *same, double *changed) const
bool SaveTrainingDump(SerializeAmount serialize_amount, const LSTMTrainer *trainer, GenericVector< char > *data) const
bool SaveTraineddata(const STRING &filename)
int training_iteration() const
int learning_iteration() const
virtual bool Serialize(SerializeAmount serialize_amount, const TessdataManager *mgr, TFile *fp) const
STRING UpdateErrorGraph(int iteration, double error_rate, const GenericVector< char > &model_data, TestCallback tester)
virtual StaticShape InputShape() const
const int kNumPagesPerBatch
bool SimpleTextOutput() const
static bool ComputeCTCTargets(const GenericVector< int > &truth_labels, int null_char, const GENERIC_2D_ARRAY< float > &outputs, NetworkIO *targets)
double error_rates_[ET_COUNT]
bool(* FileWriter)(const GenericVector< char > &data, const STRING &filename)
string VersionString() const
void ExtractBestPathAsLabels(GenericVector< int > *labels, GenericVector< int > *xcoords) const
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
bool MaintainCheckpoints(TestCallback tester, STRING *log_msg)
void add_str_double(const char *str, double number)
LossType OutputLossType() const
int prev_sample_iteration_
const double kBestCheckpointFraction
const char * string() const
bool has_special_codes() const
double SignedRand(double range)
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)
LIST search(LIST list, void *key, int_compare is_equal)
const int kNumAdjustmentIterations
void RecognizeLine(const ImageData &image_data, bool invert, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words)
bool TransitionTrainingStage(float error_threshold)
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)
STRING DecodeLabels(const GenericVector< int > &labels)
const ImageData * TrainOnLine(LSTMTrainer *samples_trainer, bool batch)
bool Serialize(FILE *fp) const
double NewSingleError(ErrorTypes type) const
CheckPointWriter checkpoint_writer_
const int kErrorGraphInterval
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
virtual R Run(A1, A2, A3, A4)=0
bool Open(const STRING &filename, FileReader reader)
bool ReadLocalTrainingDump(const TessdataManager *mgr, const char *data, int size)
const STRING & name() const
float GetLayerLearningRate(const STRING &id) const
GenericVector< double > error_buffers_[ET_COUNT]
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
virtual StaticShape OutputShape(const StaticShape &input_shape) const
std::vector< int > MapRecoder(const UNICHARSET &old_chset, const UnicharCompress &old_recoder) const
bool AnySuspiciousTruth(float confidence_thr) const
bool LoadAllTrainingData(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, bool randomly_rotate)
bool DeSerialize(bool swap, FILE *fp)
bool load_from_file(const char *const filename, bool skip_fragments)
STRING DumpFilename() const
const double kImprovementFraction
GenericVector< int > best_error_iterations_
const double kSubTrainerMarginFraction
const double kMinDivergenceRate
int FReadEndian(void *buffer, int size, int count)
virtual void DebugWeights()
GenericVector< STRING > EnumerateLayers() const
virtual R Run(A1, A2, A3)=0
static const float kMinCertainty
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
bool LoadCharsets(const TessdataManager *mgr)
void OverwriteEntry(TessdataType type, const char *data, int size)
const double kHighConfidence
void PrepareLogMsg(STRING *log_msg) const
void SetActivations(int t, int label, float ok_score)
const GenericVector< TBOX > & boxes() const
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
const UNICHARSET & GetUnicharset() const
int ReduceLayerLearningRates(double factor, int num_samples, LSTMTrainer *samples_trainer)
bool Init(const char *data_file_name)
const STRING & transcription() const
DocumentCache training_data_
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
virtual bool DeSerialize(const TessdataManager *mgr, TFile *fp)
void UpdateErrorBuffer(double new_error, ErrorTypes type)
const STRING & language() const
void ReduceLearningRates(LSTMTrainer *samples_trainer, STRING *log_msg)
int IntCastRounded(double x)
bool ReadTrainingDump(const GenericVector< char > &data, LSTMTrainer *trainer) const
void init_to_size(int size, T t)
bool DeSerialize(TFile *fp)
int checkpoint_iteration_
const double kStageTransitionThreshold
virtual int RemapOutputs(int old_no, const std::vector< int > &code_map)
void split(const char c, GenericVector< STRING > *splited)
int FRead(void *buffer, int size, int count)
SubTrainerResult UpdateSubtrainer(STRING *log_msg)
NetworkScratch scratch_space_
bool DebugLSTMTraining(const NetworkIO &inputs, const ImageData &trainingdata, const NetworkIO &fwd_outputs, const GenericVector< int > &truth_labels, const NetworkIO &outputs)
void SetVersionString(const string &v_str)
GenericVector< char > best_model_data_
void ScaleLearningRate(double factor)