tesseract  4.00.00dev
series.cpp
Go to the documentation of this file.
1 // File: series.cpp
3 // Description: Runs networks in series on the same input.
4 // Author: Ray Smith
5 // Created: Thu May 02 08:26:06 PST 2013
6 //
7 // (C) Copyright 2013, 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.
18 
19 #include "series.h"
20 
21 #include "fullyconnected.h"
22 #include "networkscratch.h"
23 #include "scrollview.h"
24 #include "tprintf.h"
25 
26 namespace tesseract {
27 
28 // ni_ and no_ will be set by AddToStack.
29 Series::Series(const STRING& name) : Plumbing(name) {
30  type_ = NT_SERIES;
31 }
32 
34 }
35 
36 // Returns the shape output from the network given an input shape (which may
37 // be partially unknown ie zero).
38 StaticShape Series::OutputShape(const StaticShape& input_shape) const {
39  StaticShape result(input_shape);
40  int stack_size = stack_.size();
41  for (int i = 0; i < stack_size; ++i) {
42  result = stack_[i]->OutputShape(result);
43  }
44  return result;
45 }
46 
47 // Sets up the network for training. Initializes weights using weights of
48 // scale `range` picked according to the random number generator `randomizer`.
49 // Note that series has its own implementation just for debug purposes.
50 int Series::InitWeights(float range, TRand* randomizer) {
51  num_weights_ = 0;
52  tprintf("Num outputs,weights in serial:\n");
53  for (int i = 0; i < stack_.size(); ++i) {
54  int weights = stack_[i]->InitWeights(range, randomizer);
55  tprintf(" %s:%d, %d\n",
56  stack_[i]->spec().string(), stack_[i]->NumOutputs(), weights);
57  num_weights_ += weights;
58  }
59  tprintf("Total weights = %d\n", num_weights_);
60  return num_weights_;
61 }
62 
63 // Sets needs_to_backprop_ to needs_backprop and returns true if
64 // needs_backprop || any weights in this network so the next layer forward
65 // can be told to produce backprop for this layer if needed.
66 bool Series::SetupNeedsBackprop(bool needs_backprop) {
67  needs_to_backprop_ = needs_backprop;
68  for (int i = 0; i < stack_.size(); ++i)
69  needs_backprop = stack_[i]->SetupNeedsBackprop(needs_backprop);
70  return needs_backprop;
71 }
72 
73 // Returns an integer reduction factor that the network applies to the
74 // time sequence. Assumes that any 2-d is already eliminated. Used for
75 // scaling bounding boxes of truth data.
76 // WARNING: if GlobalMinimax is used to vary the scale, this will return
77 // the last used scale factor. Call it before any forward, and it will return
78 // the minimum scale factor of the paths through the GlobalMinimax.
79 int Series::XScaleFactor() const {
80  int factor = 1;
81  for (int i = 0; i < stack_.size(); ++i)
82  factor *= stack_[i]->XScaleFactor();
83  return factor;
84 }
85 
86 // Provides the (minimum) x scale factor to the network (of interest only to
87 // input units) so they can determine how to scale bounding boxes.
88 void Series::CacheXScaleFactor(int factor) {
89  stack_[0]->CacheXScaleFactor(factor);
90 }
91 
92 // Runs forward propagation of activations on the input line.
93 // See NetworkCpp for a detailed discussion of the arguments.
94 void Series::Forward(bool debug, const NetworkIO& input,
95  const TransposedArray* input_transpose,
96  NetworkScratch* scratch, NetworkIO* output) {
97  int stack_size = stack_.size();
98  ASSERT_HOST(stack_size > 1);
99  // Revolving intermediate buffers.
100  NetworkScratch::IO buffer1(input, scratch);
101  NetworkScratch::IO buffer2(input, scratch);
102  // Run each network in turn, giving the output of n as the input to n + 1,
103  // with the final network providing the real output.
104  stack_[0]->Forward(debug, input, input_transpose, scratch, buffer1);
105  for (int i = 1; i < stack_size; i += 2) {
106  stack_[i]->Forward(debug, *buffer1, NULL, scratch,
107  i + 1 < stack_size ? buffer2 : output);
108  if (i + 1 == stack_size) return;
109  stack_[i + 1]->Forward(debug, *buffer2, NULL, scratch,
110  i + 2 < stack_size ? buffer1 : output);
111  }
112 }
113 
114 // Runs backward propagation of errors on the deltas line.
115 // See NetworkCpp for a detailed discussion of the arguments.
116 bool Series::Backward(bool debug, const NetworkIO& fwd_deltas,
117  NetworkScratch* scratch,
118  NetworkIO* back_deltas) {
119  if (!IsTraining()) return false;
120  int stack_size = stack_.size();
121  ASSERT_HOST(stack_size > 1);
122  // Revolving intermediate buffers.
123  NetworkScratch::IO buffer1(fwd_deltas, scratch);
124  NetworkScratch::IO buffer2(fwd_deltas, scratch);
125  // Run each network in reverse order, giving the back_deltas output of n as
126  // the fwd_deltas input to n-1, with the 0 network providing the real output.
127  if (!stack_.back()->IsTraining() ||
128  !stack_.back()->Backward(debug, fwd_deltas, scratch, buffer1))
129  return false;
130  for (int i = stack_size - 2; i >= 0; i -= 2) {
131  if (!stack_[i]->IsTraining() ||
132  !stack_[i]->Backward(debug, *buffer1, scratch,
133  i > 0 ? buffer2 : back_deltas))
134  return false;
135  if (i == 0) return needs_to_backprop_;
136  if (!stack_[i - 1]->IsTraining() ||
137  !stack_[i - 1]->Backward(debug, *buffer2, scratch,
138  i > 1 ? buffer1 : back_deltas))
139  return false;
140  }
141  return needs_to_backprop_;
142 }
143 
144 // Splits the series after the given index, returning the two parts and
145 // deletes itself. The first part, up to network with index last_start, goes
146 // into start, and the rest goes into end.
147 void Series::SplitAt(int last_start, Series** start, Series** end) {
148  *start = NULL;
149  *end = NULL;
150  if (last_start < 0 || last_start >= stack_.size()) {
151  tprintf("Invalid split index %d must be in range [0,%d]!\n",
152  last_start, stack_.size() - 1);
153  return;
154  }
155  Series* master_series = new Series("MasterSeries");
156  Series* boosted_series = new Series("BoostedSeries");
157  for (int s = 0; s <= last_start; ++s) {
158  if (s + 1 == stack_.size() && stack_[s]->type() == NT_SOFTMAX) {
159  // Change the softmax to a tanh.
160  FullyConnected* fc = static_cast<FullyConnected*>(stack_[s]);
161  fc->ChangeType(NT_TANH);
162  }
163  master_series->AddToStack(stack_[s]);
164  stack_[s] = NULL;
165  }
166  for (int s = last_start + 1; s < stack_.size(); ++s) {
167  boosted_series->AddToStack(stack_[s]);
168  stack_[s] = NULL;
169  }
170  *start = master_series;
171  *end = boosted_series;
172  delete this;
173 }
174 
175 // Appends the elements of the src series to this, removing from src and
176 // deleting it.
178  ASSERT_HOST(src->type() == NT_SERIES);
179  Series* src_series = static_cast<Series*>(src);
180  for (int s = 0; s < src_series->stack_.size(); ++s) {
181  AddToStack(src_series->stack_[s]);
182  src_series->stack_[s] = NULL;
183  }
184  delete src;
185 }
186 
187 
188 } // namespace tesseract.
bool needs_to_backprop_
Definition: network.h:287
virtual int XScaleFactor() const
Definition: series.cpp:79
virtual void CacheXScaleFactor(int factor)
Definition: series.cpp:88
virtual bool SetupNeedsBackprop(bool needs_backprop)
Definition: series.cpp:66
void SplitAt(int last_start, Series **start, Series **end)
Definition: series.cpp:147
virtual ~Series()
Definition: series.cpp:33
NetworkType type() const
Definition: network.h:112
#define tprintf(...)
Definition: tprintf.h:31
bool IsTraining() const
Definition: network.h:115
void ChangeType(NetworkType type)
#define ASSERT_HOST(x)
Definition: errcode.h:84
virtual void Forward(bool debug, const NetworkIO &input, const TransposedArray *input_transpose, NetworkScratch *scratch, NetworkIO *output)
Definition: series.cpp:94
void AppendSeries(Network *src)
Definition: series.cpp:177
virtual StaticShape OutputShape(const StaticShape &input_shape) const
Definition: series.cpp:38
PointerVector< Network > stack_
Definition: plumbing.h:133
Definition: strngs.h:45
virtual STRING spec() const
Definition: series.h:37
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)
Definition: series.cpp:116
Series(const STRING &name)
Definition: series.cpp:29
NetworkType type_
Definition: network.h:285
int NumOutputs() const
Definition: network.h:123
inT32 num_weights_
Definition: network.h:291
virtual int InitWeights(float range, TRand *randomizer)
Definition: series.cpp:50
virtual void AddToStack(Network *network)
Definition: plumbing.cpp:75