tesseract  4.00.00dev
plumbing.h
Go to the documentation of this file.
1 // File: plumbing.h
3 // Description: Base class for networks that organize other networks
4 // eg series or parallel.
5 // Author: Ray Smith
6 // Created: Mon May 12 08:11:36 PST 2014
7 //
8 // (C) Copyright 2014, Google Inc.
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 
20 #ifndef TESSERACT_LSTM_PLUMBING_H_
21 #define TESSERACT_LSTM_PLUMBING_H_
22 
23 #include "genericvector.h"
24 #include "matrix.h"
25 #include "network.h"
26 
27 namespace tesseract {
28 
29 // Holds a collection of other networks and forwards calls to each of them.
30 class Plumbing : public Network {
31  public:
32  // ni_ and no_ will be set by AddToStack.
33  explicit Plumbing(const STRING& name);
34  virtual ~Plumbing();
35 
36  // Returns the required shape input to the network.
37  virtual StaticShape InputShape() const { return stack_[0]->InputShape(); }
38  virtual STRING spec() const {
39  return "Sub-classes of Plumbing must implement spec()!";
40  }
41 
42  // Returns true if the given type is derived from Plumbing, and thus contains
43  // multiple sub-networks that can have their own learning rate.
44  virtual bool IsPlumbingType() const { return true; }
45 
46  // Suspends/Enables training by setting the training_ flag. Serialize and
47  // DeSerialize only operate on the run-time data if state is false.
48  virtual void SetEnableTraining(TrainingState state);
49 
50  // Sets flags that control the action of the network. See NetworkFlags enum
51  // for bit values.
52  virtual void SetNetworkFlags(uinT32 flags);
53 
54  // Sets up the network for training. Initializes weights using weights of
55  // scale `range` picked according to the random number generator `randomizer`.
56  // Note that randomizer is a borrowed pointer that should outlive the network
57  // and should not be deleted by any of the networks.
58  // Returns the number of weights initialized.
59  virtual int InitWeights(float range, TRand* randomizer);
60  // Recursively searches the network for softmaxes with old_no outputs,
61  // and remaps their outputs according to code_map. See network.h for details.
62  int RemapOutputs(int old_no, const std::vector<int>& code_map) override;
63 
64  // Converts a float network to an int network.
65  virtual void ConvertToInt();
66 
67  // Provides a pointer to a TRand for any networks that care to use it.
68  // Note that randomizer is a borrowed pointer that should outlive the network
69  // and should not be deleted by any of the networks.
70  virtual void SetRandomizer(TRand* randomizer);
71 
72  // Adds the given network to the stack.
73  virtual void AddToStack(Network* network);
74 
75  // Sets needs_to_backprop_ to needs_backprop and returns true if
76  // needs_backprop || any weights in this network so the next layer forward
77  // can be told to produce backprop for this layer if needed.
78  virtual bool SetupNeedsBackprop(bool needs_backprop);
79 
80  // Returns an integer reduction factor that the network applies to the
81  // time sequence. Assumes that any 2-d is already eliminated. Used for
82  // scaling bounding boxes of truth data.
83  // WARNING: if GlobalMinimax is used to vary the scale, this will return
84  // the last used scale factor. Call it before any forward, and it will return
85  // the minimum scale factor of the paths through the GlobalMinimax.
86  virtual int XScaleFactor() const;
87 
88  // Provides the (minimum) x scale factor to the network (of interest only to
89  // input units) so they can determine how to scale bounding boxes.
90  virtual void CacheXScaleFactor(int factor);
91 
92  // Provides debug output on the weights.
93  virtual void DebugWeights();
94 
95  // Returns the current stack.
96  const PointerVector<Network>& stack() const {
97  return stack_;
98  }
99  // Returns a set of strings representing the layer-ids of all layers below.
100  void EnumerateLayers(const STRING* prefix,
101  GenericVector<STRING>* layers) const;
102  // Returns a pointer to the network layer corresponding to the given id.
103  Network* GetLayer(const char* id) const;
104  // Returns the learning rate for a specific layer of the stack.
105  float LayerLearningRate(const char* id) const {
106  const float* lr_ptr = LayerLearningRatePtr(id);
107  ASSERT_HOST(lr_ptr != NULL);
108  return *lr_ptr;
109  }
110  // Scales the learning rate for a specific layer of the stack.
111  void ScaleLayerLearningRate(const char* id, double factor) {
112  float* lr_ptr = LayerLearningRatePtr(id);
113  ASSERT_HOST(lr_ptr != NULL);
114  *lr_ptr *= factor;
115  }
116  // Returns a pointer to the learning rate for the given layer id.
117  float* LayerLearningRatePtr(const char* id) const;
118 
119  // Writes to the given file. Returns false in case of error.
120  virtual bool Serialize(TFile* fp) const;
121  // Reads from the given file. Returns false in case of error.
122  virtual bool DeSerialize(TFile* fp);
123 
124  // Updates the weights using the given learning rate, momentum and adam_beta.
125  // num_samples is used in the adam computation iff use_adam_ is true.
126  void Update(float learning_rate, float momentum, float adam_beta,
127  int num_samples) override;
128  // Sums the products of weight updates in *this and other, splitting into
129  // positive (same direction) in *same and negative (different direction) in
130  // *changed.
131  virtual void CountAlternators(const Network& other, double* same,
132  double* changed) const;
133 
134  protected:
135  // The networks.
137  // Layer-specific learning rate iff network_flags_ & NF_LAYER_SPECIFIC_LR.
138  // One element for each element of stack_.
140 };
141 
142 } // namespace tesseract.
143 
144 #endif // TESSERACT_LSTM_PLUMBING_H_
145 
virtual void SetEnableTraining(TrainingState state)
Definition: plumbing.cpp:34
virtual int InitWeights(float range, TRand *randomizer)
Definition: plumbing.cpp:53
Network * GetLayer(const char *id) const
Definition: plumbing.cpp:158
void ScaleLayerLearningRate(const char *id, double factor)
Definition: plumbing.h:111
virtual void CountAlternators(const Network &other, double *same, double *changed) const
Definition: plumbing.cpp:237
virtual StaticShape InputShape() const
Definition: plumbing.h:37
uint32_t uinT32
Definition: host.h:39
float * LayerLearningRatePtr(const char *id) const
Definition: plumbing.cpp:171
virtual bool Serialize(TFile *fp) const
Definition: plumbing.cpp:185
void Update(float learning_rate, float momentum, float adam_beta, int num_samples) override
Definition: plumbing.cpp:219
Plumbing(const STRING &name)
Definition: plumbing.cpp:25
virtual void SetRandomizer(TRand *randomizer)
Definition: plumbing.cpp:79
virtual int XScaleFactor() const
Definition: plumbing.cpp:123
virtual bool DeSerialize(TFile *fp)
Definition: plumbing.cpp:200
PointerVector< Network > stack_
Definition: plumbing.h:136
virtual bool SetupNeedsBackprop(bool needs_backprop)
Definition: plumbing.cpp:103
virtual bool IsPlumbingType() const
Definition: plumbing.h:44
const PointerVector< Network > & stack() const
Definition: plumbing.h:96
int RemapOutputs(int old_no, const std::vector< int > &code_map) override
Definition: plumbing.cpp:62
virtual void ConvertToInt()
Definition: plumbing.cpp:71
Definition: strngs.h:45
TrainingState
Definition: network.h:92
const STRING & name() const
Definition: network.h:138
#define ASSERT_HOST(x)
Definition: errcode.h:84
virtual STRING spec() const
Definition: plumbing.h:38
virtual ~Plumbing()
Definition: plumbing.cpp:29
virtual void SetNetworkFlags(uinT32 flags)
Definition: plumbing.cpp:42
virtual void CacheXScaleFactor(int factor)
Definition: plumbing.cpp:129
virtual void DebugWeights()
Definition: plumbing.cpp:136
GenericVector< float > learning_rates_
Definition: plumbing.h:139
float LayerLearningRate(const char *id) const
Definition: plumbing.h:105
virtual void AddToStack(Network *network)
Definition: plumbing.cpp:85
void EnumerateLayers(const STRING *prefix, GenericVector< STRING > *layers) const
Definition: plumbing.cpp:142