GaussianLayer.h
Go to the documentation of this file.
1 /*!
2  *
3  *
4  * \brief -
5  *
6  * \author -
7  * \date -
8  *
9  *
10  * \par Copyright 1995-2015 Shark Development Team
11  *
12  * <BR><HR>
13  * This file is part of Shark.
14  * <http://image.diku.dk/shark/>
15  *
16  * Shark is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU Lesser General Public License as published
18  * by the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * Shark is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24  * GNU Lesser General Public License for more details.
25  *
26  * You should have received a copy of the GNU Lesser General Public License
27  * along with Shark. If not, see <http://www.gnu.org/licenses/>.
28  *
29  */
30 #ifndef SHARK_UNSUPERVISED_RBM_NEURONLAYERS_GAUSSIANLAYER_H
31 #define SHARK_UNSUPERVISED_RBM_NEURONLAYERS_GAUSSIANLAYER_H
32 
33 #include <shark/LinAlg/Base.h>
35 #include <shark/Rng/Normal.h>
38 #include <shark/Core/Math.h>
40 #include <shark/Core/OpenMP.h>
41 namespace shark{
42 
43 ///\brief A layer of Gaussian neurons.
44 ///
45 /// For a Gaussian neuron/variable the conditional probability distribution of the
46 /// state of the variable given the state of the other layer is given by a Gaussian
47 /// distribution with the input of the neuron as mean and unit variance.
49 private:
50  RealVector m_bias; ///the bias terms associated with the neurons
51 public:
52  ///the state space of this neuron is binary
54 
55  ///\brief The sufficient statistics for the Guassian Layer stores the mean of the neuron and the inverse temperature
56  typedef RealVector SufficientStatistics;
57  ///\brief Sufficient statistics of a batch of data.
59 
60  /// \brief Returns the bias values of the units.
61  const RealVector& bias()const{
62  return m_bias;
63  }
64  /// \brief Returns the bias values of the units.
65  RealVector& bias(){
66  return m_bias;
67  }
68 
69  ///\brief Resizes this neuron layer.
70  ///
71  ///@param newSize number of neurons in the layer
72  void resize(std::size_t newSize){
73  m_bias.resize(newSize);
74  }
75 
76  ///\brief Returns the number of neurons of this layer.
77  std::size_t size()const{
78  return m_bias.size();
79  }
80 
81  /// \brief Takes the input of the neuron and estimates the expectation of the response of the neuron.
82  ///
83  /// @param input the batch of inputs of the neuron
84  /// @param statistics sufficient statistics containing the mean of the resulting Gaussian distribution
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)) = row(input,i)*beta(i)+m_bias;
94  }
95  }
96 
97 
98  /// \brief Given a the precomputed statistics (the mean of the Gaussian), the elements of the vector are sampled.
99  /// This happens either with Gibbs-Sampling or Flip-the-State sampling.
100  /// 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.
101  /// 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
102  /// into states with higher probability. THIS IS NOT IMPLEMENTED YET and alpha is ignored!
103  ///
104  ///
105  /// @param statistics sufficient statistics containing the mean of the conditional Gaussian distribution of the neurons
106  /// @param state the state matrix that will hold the sampled states
107  /// @param alpha factor changing from gibbs to flip-the state sampling. 0<=alpha<=1
108  /// @param rng the random number generator used for sampling
109  template<class Matrix, class Rng>
110  void sample(StatisticsBatch const& statistics, Matrix& state, double alpha, Rng& rng) const{
111  SIZE_CHECK(statistics.size2() == size());
112  SIZE_CHECK(statistics.size1() == state.size1());
113  SIZE_CHECK(statistics.size2() == state.size2());
114 
116  for(std::size_t i = 0; i != state.size1();++i){
117  for(std::size_t j = 0; j != state.size2();++j){
118  Normal<Rng> normal(rng,statistics(i,j),1.0);
119  state(i,j) = normal();
120  }
121  }
122  }
123  (void) alpha;
124  }
125 
126  /// \brief Computes the log of the probability of the given states in the conditional distribution
127  ///
128  /// Currently it is only possible to compute the case with alpha=0
129  ///
130  /// @param statistics the statistics of the conditional distribution
131  /// @param state the state to check
132  template<class Matrix>
133  RealVector logProbability(StatisticsBatch const& statistics, Matrix const& state) const{
134  SIZE_CHECK(statistics.size2() == size());
135  SIZE_CHECK(statistics.size1() == state.size1());
136  SIZE_CHECK(statistics.size2() == state.size2());
137 
138  RealVector logProbabilities(state.size1(),1.0);
139  for(std::size_t s = 0; s != state.size1();++s){
140  for(std::size_t i = 0; i != state.size2();++i){
141  logProbabilities(s) -= 0.5*sqr(statistics(s,i)-state(s,i));
142  }
143  }
144  return logProbabilities;
145  }
146 
147  /// \brief Transforms the current state of the neurons for the multiplication with the weight matrix of the RBM,
148  /// i.e. calculates the value of the phi-function used in the interaction term.
149  /// In the case of Gaussian neurons the phi-function is just the identity.
150  ///
151  /// @param state the state matrix of the neuron layer
152  /// @return the value of the phi-function
153  template<class Matrix>
154  Matrix const& phi(Matrix const& state)const{
155  SIZE_CHECK(state.size2() == size());
156  return state;
157  }
158 
159 
160  /// \brief Returns the expectation of the phi-function.
161  /// @param statistics the sufficient statistics (the mean of the distribution).
162  RealMatrix const& expectedPhiValue(StatisticsBatch const& statistics)const{
163  SIZE_CHECK(statistics.size2() == size());
164  return statistics;
165  }
166  /// \brief Returns the mean given the state of the connected layer, i.e. in this case the mean of the Gaussian
167  ///
168  /// @param statistics the sufficient statistics of the layer for a whole batch
169  RealMatrix const& mean(StatisticsBatch const& statistics)const{
170  SIZE_CHECK(statistics.size2() == size());
171  return statistics;
172  }
173 
174  /// \brief The energy term this neuron adds to the energy function for a batch of inputs.
175  ///
176  /// @param state the state of the neuron layer
177  /// @param beta the inverse temperature of the i-th state
178  /// @return the energy term of the neuron layer
179  template<class Matrix, class BetaVector>
180  RealVector energyTerm(Matrix const& state, BetaVector const& beta)const{
181  SIZE_CHECK(state.size2() == size());
182  SIZE_CHECK(state.size1() == beta.size());
183  //the following code does for batches the equivalent thing to:
184  //return beta * inner_prod(m_bias,state) - norm_sqr(state)/2.0;
185 
186  std::size_t batchSize = state.size1();
187  RealVector energies = prod(state,m_bias);
188  noalias(energies) *= beta;
189  for(std::size_t i = 0; i != batchSize; ++i){
190  energies(i) -= norm_sqr(row(state,i))/2.0;
191  }
192  return energies;
193 
194  }
195 
196 
197  ///\brief Sums over all possible values of the terms of the energy function which depend on the this layer and returns the logarithmic result.
198  ///
199  ///This function is called by Energy when the unnormalized marginal probability of the connected layer is to be computed.
200  ///This function calculates the part which depends on the neurons which are to be marginalized out.
201  ///(In the case of the binary hidden neuron, this is the term \f$ \log \sum_h e^{\vec h^T W \vec v+ \vec h^T \vec c} \f$).
202  ///The rest is calculated by the energy function.
203  ///In the general case of a hidden layer, this function calculates \f$ \log \int_h e^(\phi_h(\vec h)^T W \phi_v(\vec v)+f_h(\vec h) ) \f$
204  ///where f_h is the energy term of this.
205  ///
206  /// @param inputs the inputs of the neurons they get from the other layer
207  /// @param beta the inverse temperature of the RBM
208  /// @return the marginal distribution of the connected layer
209  template<class Input>
210  double logMarginalize(const Input& inputs, double beta) const{
211  SIZE_CHECK(inputs.size() == size());
212  double lnResult = 0;
213  double logNormalizationTerm = std::log(SQRT_2_PI) - 0.5 * std::log(beta);
214 
215  for(std::size_t i = 0; i != size(); ++i){
216  lnResult += 0.5 * sqr(inputs(i)+m_bias(i))*beta;
217  lnResult += logNormalizationTerm;
218  }
219  return lnResult;
220  }
221 
222 
223  ///\brief Calculates the expectation of the derivatives of the energy term of this neuron layer with respect to it's parameters - the bias weights.
224  /// The expectation is taken with respect to the conditional probability distribution of the layer given the state of the connected layer.
225  ///
226  ///This function takes a batch of samples and extracts the required informations out of it.
227  ///@param derivative the derivative with respect to the parameters, the result is added on top of it to accumulate derivatives
228  ///@param samples the samples from which the informations can be extracted
229  template<class Vector, class SampleBatch>
230  void expectedParameterDerivative(Vector& derivative, SampleBatch const& samples )const{
231  SIZE_CHECK(derivative.size() == size());
232  sum_rows(samples.statistics,derivative);
233  }
234 
235  template<class Vector, class SampleBatch, class Vector2 >
236  void expectedParameterDerivative(Vector& derivative, SampleBatch const& samples, Vector2 const& weights )const{
237  SIZE_CHECK(derivative.size() == size());
238  noalias(derivative) += prod(weights,samples.statistics);
239  }
240 
241  ///\brief Calculates the derivatives of the energy term of this neuron layer with respect to it's parameters - the bias weights.
242  ///
243  ///This function takes a batch of samples and extracts the required informations out of it.
244  ///@param derivative the derivative with respect to the parameters, the result is added on top of it to accumulate derivatives
245  ///@param samples the sample from which the informations can be extracted
246  template<class Vector, class SampleBatch>
247  void parameterDerivative(Vector& derivative, SampleBatch const& samples)const{
248  SIZE_CHECK(derivative.size() == size());
249  sum_rows(samples.state,derivative);
250  }
251 
252  ///\brief Calculates the derivatives of the energy term of this neuron layer with respect to it's parameters - the bias weights.
253  ///
254  ///This function takes a batch of samples and calculates a weighted derivative
255  ///@param derivative the derivative with respect to the parameters, the result is added on top of it to accumulate derivatives
256  ///@param samples the sample from which the informations can be extracted
257  ///@param weights the weights for the single sample derivatives
258  template<class Vector, class SampleBatch, class WeightVector>
259  void parameterDerivative(Vector& derivative, SampleBatch const& samples, WeightVector const& weights)const{
260  SIZE_CHECK(derivative.size() == size());
261  noalias(derivative) += prod(weights,samples.state);
262  }
263 
264  ///\brief Returns the vector with the parameters associated with the neurons in the layer.
265  RealVector parameterVector()const{
266  return m_bias;
267  }
268 
269  ///\brief Returns the vector with the parameters associated with the neurons in the layer.
270  void setParameterVector(RealVector const& newParameters){
271  m_bias = newParameters;
272  }
273 
274  ///\brief Returns the number of the parameters associated with the neurons in the layer.
275  std::size_t numberOfParameters()const{
276  return size();
277  }
278 
279  /// \brief Reads the bias parameters from an archive.
280  void read( InArchive & archive ){
281  archive >> m_bias;
282  }
283  /// \brief Writes the bias parameters to an archive.
284  void write( OutArchive & archive ) const{
285  archive << m_bias;
286  }
287 };
288 
289 }
290 #endif