BipolarLayer.h
Go to the documentation of this file.
1 /*!
2  *
3  * \brief Implements the bipolar (-1,1) state neuron layer
4  *
5  * \author Asja Fischer
6  * \date 2013
7  *
8  * \par Copyright 1995-2015 Shark Development Team
9  *
10  * <BR><HR>
11  * This file is part of Shark.
12  * <http://image.diku.dk/shark/>
13  *
14  * Shark is free software: you can redistribute it and/or modify
15  * it under the terms of the GNU Lesser General Public License as published
16  * by the Free Software Foundation, either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * Shark is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22  * GNU Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public License
25  * along with Shark. If not, see <http://www.gnu.org/licenses/>.
26  *
27  */
28 #ifndef SHARK_UNSUPERVISED_RBM_NEURONLAYERS_BIPOLARLAYER_H
29 #define SHARK_UNSUPERVISED_RBM_NEURONLAYERS_BIPOLARLAYER_H
30 
33 #include <shark/LinAlg/Base.h>
35 #include <shark/Rng/Bernoulli.h>
37 #include <shark/Core/OpenMP.h>
38 namespace shark{
39 
40 ///\brief Layer of bipolar units taking values in {-1,1}.
41 
42 ///A neuron in a BipolarLayer takes values in {-1,1} and the conditional probability to be 1
43 ///given the states of the neurons in the connected layer is determined by the sigmoid function
44 ///and the input it gets from the connected layer.
46 private:
47  ///\brief The bias terms associated with the neurons.
48  RealVector m_bias;
49 public:
50  ///the state space of this neuron is binary
52 
53  ///\brief The sufficient statistics for the Binary Layer store the probability for a neuron to be on
54  typedef RealVector SufficientStatistics;
55  ///\brief Sufficient statistics of a batch of data.
57 
58  /// \brief Returns the bias values of the units.
59  const RealVector& bias()const{
60  return m_bias;
61  }
62 
63  /// \brief Returns the bias values of the units.
64  RealVector& bias(){
65  return m_bias;
66  }
67 
68  ///\brief Resizes this neuron layer.
69  ///
70  ///@param newSize number of neurons in the layer
71  void resize(std::size_t newSize){
72  m_bias.resize(newSize);
73  }
74 
75  ///\brief Returns the number of neurons of this layer.
76  std::size_t size()const{
77  return m_bias.size();
78  }
79 
80  /// \brief Takes the input of the neuron and calculates the distribution of the neurons
81  /// For binary neuronsthis is identical with the conditional probability for the neuron to be on given the state of the connected layer.
82  ///
83  /// @param input the batch of inputs of the neuron
84  /// @param statistics sufficient statistics containing the probabilities of the neurons to be one
85  /// @param beta the inverse Temperature of the RBM (typically 1) for the whole batch
86  template<class Input, class BetaVector>
87  void sufficientStatistics(Input const& input, StatisticsBatch& statistics,BetaVector const& beta)const{ // \todo: auch hier noch mal namen ueberdenken
88  SIZE_CHECK(input.size2() == size());
89  SIZE_CHECK(statistics.size2() == size());
90  SIZE_CHECK(input.size1() == statistics.size1());
91 
92  for(std::size_t i = 0; i != input.size1(); ++i){
93  noalias(row(statistics,i)) = sigmoid(2*(row(input,i)+m_bias)*beta(i));
94  }
95  }
96 
97  /// \brief Samples from the distribution using either Gibbs- or flip-the-state sampling.
98  ///
99  /// For alpha= 0 gibbs sampling is performed. That is the next state for neuron i is directly taken from the conditional distribution of the i-th neuron.
100  /// In the case of alpha=1, flip-the-state sampling is performed, which takes the last state into account and tries to do deterministically jump
101  /// into states with higher probability. This is counterbalanced by a higher chance to jump back into a lower probability state in later steps.
102  /// For alpha between 0 and 1 a mixture of both is performed.
103  ///
104  /// @param statistics sufficient statistics containing the probabilities of the neurons to be one
105  /// @param state the state vector that shell hold the sampled states
106  /// @param alpha factor changing from gibbs to flip-the state sampling. 0<=alpha<=1
107  /// @param rng the random number generator used for sampling
108  template<class Matrix, class Rng>
109  void sample(StatisticsBatch const& statistics, Matrix& state, double alpha, Rng& rng) const{
110  SIZE_CHECK(statistics.size2() == size());
111  SIZE_CHECK(statistics.size1() == state.size1());
112  SIZE_CHECK(statistics.size2() == state.size2());
113 
115  Bernoulli<Rng> coinToss(rng,0.5);
116  if(alpha == 0.0){//special case: normal gibbs sampling
117  for(std::size_t s = 0; s != state.size1();++s){
118  for(std::size_t i = 0; i != state.size2();++i){
119  state(s,i) = coinToss(statistics(s,i));
120  if(state(s,i)==0) state(s,i)=-1.;
121  }
122  }
123  }
124  else{//flip-the state sampling
125  for(size_t s = 0; s != state.size1(); ++s){
126  for (size_t i = 0; i != state.size2(); i++) {
127  double prob = statistics(s,i);
128  if (state(s,i) == -1) {
129  if (prob <= 0.5) {
130  prob = (1. - alpha) * prob + alpha * prob / (1. - prob);
131  } else {
132  prob = (1. - alpha) * prob + alpha;
133  }
134  } else {
135  if (prob >= 0.5) {
136  prob = (1. - alpha) * prob + alpha * (1. - (1. - prob) / prob);
137  } else {
138  prob = (1. - alpha) * prob;
139  }
140  }
141  state(s,i) = coinToss(prob);
142  if(state(s,i)==0) state(s,i)=-1.;
143  }
144  }
145  }
146  }
147  }
148 
149  /// \brief Computes the log of the probability of the given states in the conditional distribution
150  ///
151  /// Currently it is only possible to compute the case with alpha=0
152  ///
153  /// @param statistics the statistics of the conditional distribution
154  /// @param state the state to check
155  template<class Matrix>
156  RealVector logProbability(StatisticsBatch const& statistics, Matrix const& state) const{
157  SIZE_CHECK(statistics.size2() == size());
158  SIZE_CHECK(statistics.size1() == state.size1());
159  SIZE_CHECK(statistics.size2() == state.size2());
160 
161  RealVector logProbabilities(state.size1(),1.0);
162  for(std::size_t s = 0; s != state.size1();++s){
163  for(std::size_t i = 0; i != state.size2();++i){
164  logProbabilities(s) += (state(s,i) > 0.0)? std::log(statistics(s,i)) : std::log(1-statistics(s,i));
165  }
166  }
167  return logProbabilities;
168  }
169 
170  /// \brief Transforms the current state of the neurons for the multiplication with the weight matrix of the RBM,
171  /// i.e. calculates the value of the phi-function used in the interaction term.
172  /// In the case of bipolar neurons the phi-function is just the identity.
173  ///
174  /// @param state the state matrix of the neuron layer
175  /// @return the value of the phi-function
176  template<class Matrix>
177  Matrix const& phi(Matrix const& state)const{
178  SIZE_CHECK(state.size2() == size());
179  return state;
180  }
181 
182 
183  /// \brief Returns the conditional expectation of the phi-function given the state of the connected layer,
184  ///
185  /// @param statistics the sufficient statistics of the layer
186  RealMatrix expectedPhiValue(StatisticsBatch const& statistics)const{
187  //calculation of the expectation: 1*P(h_i=1|v)- 1*(1-P(h_i=1|v))= 2*P(h_i=1|v)-1
188  return 2*statistics - 1;
189  }
190 
191  /// \brief Returns the mean of the distribution
192  ///
193  /// @param statistics the sufficient statistics of the layer for a whole batch
194  RealMatrix mean(StatisticsBatch const& statistics)const{
195  SIZE_CHECK(statistics.size2() == size());
196  //calculation of the expectation: 1*P(h_i=1|v)- 1*(1-P(h_i=1|v))= 2*P(h_i=1|v)-1
197  return 2*statistics - 1;
198  }
199 
200 
201  /// \brief Returns the energy term this neuron adds to the energy function.
202  ///
203  /// @param state the state of the neuron layer
204  /// @param beta the inverse temperature of the i-th state
205  /// @return the energy term of the neuron layer
206  template<class Matrix, class BetaVector>
207  RealVector energyTerm(Matrix const& state, BetaVector const& beta)const{
208  SIZE_CHECK(state.size2() == size());
209 
210  RealVector energies = beta*prod(state,m_bias);
211  return energies;
212  }
213 
214 
215  ///\brief Sums over all possible values of the terms of the energy function which depend on the this layer and returns the logarithmic result.
216  ///
217  ///This function is called by Energy when the unnormalized marginal probability of the connected layer is to be computed.
218  ///This function calculates the part which depends on the neurons which are to be marginalized out.
219  ///(In the case of the bipolar hidden neuron, this is the term \f$ \sum_h e^{\vec h^T W \vec v+ \vec h^T \vec c} \f$).
220  ///The rest is calculated by the energy function.
221  ///
222  /// @param inputs the inputs of the neurons they get from the other layer
223  /// @param beta the inverse temperature of the RBM
224  /// @return the marginal distribution of the connected layer
225  template<class Input>
226  double logMarginalize(Input const& inputs, double beta) const{
227  SIZE_CHECK(inputs.size() == size());
228  long double logFactorization = 0;
229  for(std::size_t i = 0; i != inputs.size(); ++i){
230  long double arg = std::abs((inputs(i)+m_bias(i))*beta);
231  logFactorization += softPlus(-2*arg)+arg;
232  }
233  return logFactorization;
234  }
235 
236 
237  ///\brief Calculates the expectation of the derivatives of the energy term of this neuron layer with respect to it's parameters - the bias weights.
238  /// The expectation is taken with respect to the conditional probability distribution of the layer given the state of the connected layer.
239  ///
240  ///This function takes a batch of samples and extracts the required informations out of it.
241  ///@param derivative the derivative with respect to the parameters, the result is added on top of it to accumulate derivatives
242  ///@param samples the samples from which the informations can be extracted
243  template<class Vector, class SampleBatch>
244  void expectedParameterDerivative(Vector& derivative, SampleBatch const& samples )const{
245  SIZE_CHECK(derivative.size() == size());
246  sumRows(2*samples.statistics,derivative);
247  derivative -= samples.size();
248  }
249 
250  ///\brief Calculates the expectation of the derivatives of the energy term of this neuron layer with respect to it's parameters - the bias weights.
251  /// The expectation is taken with respect to the conditional probability distribution of the layer given the state of the connected layer.
252  ///
253  ///This function takes a batch of samples and weights the results
254  ///@param derivative the derivative with respect to the parameters, the result is added on top of it to accumulate derivatives
255  ///@param samples the samples from which the informations can be extracted
256  ///@param weights The weights for alle samples
257  template<class Vector, class SampleBatch, class WeightVector>
258  void expectedParameterDerivative(Vector& derivative, SampleBatch const& samples, WeightVector const& weights )const{
259  SIZE_CHECK(derivative.size() == size());
260  noalias(derivative) += 2*prod(weights,samples.statistics) - sum(weights);
261  }
262 
263 
264  ///\brief Calculates the derivatives of the energy term of this neuron layer with respect to it's parameters - the bias weights.
265  ///
266  ///This function takes a batch of samples and extracts the required informations out of it.
267  ///@param derivative the derivative with respect to the parameters, the result is added on top of it to accumulate derivatives
268  ///@param samples the sample from which the informations can be extracted
269  template<class Vector, class SampleBatch>
270  void parameterDerivative(Vector& derivative, SampleBatch const& samples)const{
271  SIZE_CHECK(derivative.size() == size());
272  sumRows(samples.state,derivative);
273  }
274 
275  ///\brief Calculates the derivatives of the energy term of this neuron layer with respect to it's parameters - the bias weights.
276  ///
277  ///This function takes a batch of samples and calculates a weighted derivative
278  ///@param derivative the derivative with respect to the parameters, the result is added on top of it to accumulate derivatives
279  ///@param samples the sample from which the informations can be extracted
280  ///@param weights the weights for the single sample derivatives
281  template<class Vector, class SampleBatch, class WeightVector>
282  void parameterDerivative(Vector& derivative, SampleBatch const& samples, WeightVector const& weights)const{
283  SIZE_CHECK(derivative.size() == size());
284  noalias(derivative) += prod(weights,samples.state);
285  }
286 
287  /// \brief Returns the vector with the parameters associated with the neurons in the layer, i.e. the bias vector.
288  RealVector parameterVector()const{
289  return m_bias;
290  }
291 
292  /// \brief Sets the parameters associated with the neurons in the layer, i.e. the bias vector.
293  void setParameterVector(RealVector const& newParameters){
294  m_bias = newParameters;
295  }
296 
297  /// \brief Returns the number of the parameters associated with the neurons in the layer.
298  std::size_t numberOfParameters()const{
299  return size();
300  }
301 
302  /// \brief Reads the bias vector from an archive.
303  ///
304  /// @param archive the archive
305  void read( InArchive & archive ){
306  archive >> m_bias;
307  }
308 
309  /// \brief Writes the bias vector to an archive.
310  ///
311  /// @param archive the archive
312  void write( OutArchive & archive ) const{
313  archive << m_bias;
314  }
315 };
316 
317 }
318 #endif