tesseract  4.00.00dev
params_model.cpp
Go to the documentation of this file.
1 // File: params_model.cpp
3 // Description: Trained language model parameters.
4 // Author: David Eger
5 // Created: Mon Jun 11 11:26:42 PDT 2012
6 //
7 // (C) Copyright 2012, Google Inc.
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
19 
20 #include "params_model.h"
21 
22 #include <ctype.h>
23 #include <math.h>
24 #include <stdio.h>
25 
26 #include "bitvector.h"
27 #include "tprintf.h"
28 
29 namespace tesseract {
30 
31 // Scale factor to apply to params model scores.
32 static const float kScoreScaleFactor = 100.0f;
33 // Minimum cost result to return.
34 static const float kMinFinalCost = 0.001f;
35 // Maximum cost result to return.
36 static const float kMaxFinalCost = 100.0f;
37 
39  for (int p = 0; p < PTRAIN_NUM_PASSES; ++p) {
40  tprintf("ParamsModel for pass %d lang %s\n", p, lang_.string());
41  for (int i = 0; i < weights_vec_[p].size(); ++i) {
42  tprintf("%s = %g\n", kParamsTrainingFeatureTypeName[i],
43  weights_vec_[p][i]);
44  }
45  }
46 }
47 
48 void ParamsModel::Copy(const ParamsModel &other_model) {
49  for (int p = 0; p < PTRAIN_NUM_PASSES; ++p) {
50  weights_vec_[p] = other_model.weights_for_pass(
51  static_cast<PassEnum>(p));
52  }
53 }
54 
55 // Given a (modifiable) line, parse out a key / value pair.
56 // Return true on success.
57 bool ParamsModel::ParseLine(char *line, char** key, float *val) {
58  if (line[0] == '#')
59  return false;
60  int end_of_key = 0;
61  while (line[end_of_key] && !isspace(line[end_of_key])) end_of_key++;
62  if (!line[end_of_key]) {
63  tprintf("ParamsModel::Incomplete line %s\n", line);
64  return false;
65  }
66  line[end_of_key++] = 0;
67  *key = line;
68  if (sscanf(line + end_of_key, " %f", val) != 1)
69  return false;
70  return true;
71 }
72 
73 // Applies params model weights to the given features.
74 // Assumes that features is an array of size PTRAIN_NUM_FEATURE_TYPES.
75 // The cost is set to a number that can be multiplied by the outline length,
76 // as with the old ratings scheme. This enables words of different length
77 // and combinations of words to be compared meaningfully.
78 float ParamsModel::ComputeCost(const float features[]) const {
79  float unnorm_score = 0.0;
80  for (int f = 0; f < PTRAIN_NUM_FEATURE_TYPES; ++f) {
81  unnorm_score += weights_vec_[pass_][f] * features[f];
82  }
83  return ClipToRange(-unnorm_score / kScoreScaleFactor,
84  kMinFinalCost, kMaxFinalCost);
85 }
86 
87 bool ParamsModel::Equivalent(const ParamsModel &that) const {
88  float epsilon = 0.0001;
89  for (int p = 0; p < PTRAIN_NUM_PASSES; ++p) {
90  if (weights_vec_[p].size() != that.weights_vec_[p].size()) return false;
91  for (int i = 0; i < weights_vec_[p].size(); i++) {
92  if (weights_vec_[p][i] != that.weights_vec_[p][i] &&
93  fabs(weights_vec_[p][i] - that.weights_vec_[p][i]) > epsilon)
94  return false;
95  }
96  }
97  return true;
98 }
99 
101  const char *lang,
102  const char *full_path) {
103  TFile fp;
104  if (!fp.Open(full_path, nullptr)) {
105  tprintf("Error opening file %s\n", full_path);
106  return false;
107  }
108  return LoadFromFp(lang, &fp);
109 }
110 
111 bool ParamsModel::LoadFromFp(const char *lang, TFile *fp) {
112  const int kMaxLineSize = 100;
113  char line[kMaxLineSize];
114  BitVector present;
116  lang_ = lang;
117  // Load weights for passes with adaption on.
118  GenericVector<float> &weights = weights_vec_[pass_];
120 
121  while (fp->FGets(line, kMaxLineSize) != nullptr) {
122  char *key = nullptr;
123  float value;
124  if (!ParseLine(line, &key, &value))
125  continue;
126  int idx = ParamsTrainingFeatureByName(key);
127  if (idx < 0) {
128  tprintf("ParamsModel::Unknown parameter %s\n", key);
129  continue;
130  }
131  if (!present[idx]) {
132  present.SetValue(idx, true);
133  }
134  weights[idx] = value;
135  }
136  bool complete = (present.NumSetBits() == PTRAIN_NUM_FEATURE_TYPES);
137  if (!complete) {
138  for (int i = 0; i < PTRAIN_NUM_FEATURE_TYPES; i++) {
139  if (!present[i]) {
140  tprintf("Missing field %s.\n", kParamsTrainingFeatureTypeName[i]);
141  }
142  }
143  lang_ = "";
144  weights.truncate(0);
145  }
146  return complete;
147 }
148 
149 bool ParamsModel::SaveToFile(const char *full_path) const {
150  const GenericVector<float> &weights = weights_vec_[pass_];
151  if (weights.size() != PTRAIN_NUM_FEATURE_TYPES) {
152  tprintf("Refusing to save ParamsModel that has not been initialized.\n");
153  return false;
154  }
155  FILE *fp = fopen(full_path, "wb");
156  if (!fp) {
157  tprintf("Could not open %s for writing.\n", full_path);
158  return false;
159  }
160  bool all_good = true;
161  for (int i = 0; i < weights.size(); i++) {
162  if (fprintf(fp, "%s %f\n", kParamsTrainingFeatureTypeName[i], weights[i])
163  < 0) {
164  all_good = false;
165  }
166  }
167  fclose(fp);
168  return all_good;
169 }
170 
171 } // namespace tesseract
int NumSetBits() const
Definition: bitvector.cpp:212
void init_to_size(int size, T t)
bool Equivalent(const ParamsModel &that) const
voidpf void uLong size
Definition: ioapi.h:39
bool LoadFromFp(const char *lang, TFile *fp)
void SetValue(int index, bool value)
Definition: bitvector.h:78
float ComputeCost(const float features[]) const
#define tprintf(...)
Definition: tprintf.h:31
const char * string() const
Definition: strngs.cpp:198
void truncate(int size)
void Init(int length)
Definition: bitvector.cpp:132
int size() const
Definition: genericvector.h:72
void Copy(const ParamsModel &other_model)
bool SaveToFile(const char *full_path) const
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:122
int ParamsTrainingFeatureByName(const char *name)
const GenericVector< float > & weights() const
Definition: params_model.h:66
bool LoadFromFile(const char *lang, const char *full_path)
bool Open(const STRING &filename, FileReader reader)
Definition: serialis.cpp:38
char * FGets(char *buffer, int buffer_size)
Definition: serialis.cpp:86
const char features[]
Definition: feature_tests.c:2
const GenericVector< float > & weights_for_pass(PassEnum pass) const
Definition: params_model.h:69