SHOGUN  4.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
KLCholeskyInferenceMethod.cpp
Go to the documentation of this file.
1  /*
2  * Copyright (c) The Shogun Machine Learning Toolbox
3  * Written (w) 2014 Wu Lin
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright notice,
12  * this list of conditions and the following disclaimer in the documentation
13  * and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * The views and conclusions contained in the software and documentation are those
27  * of the authors and should not be interpreted as representing official policies,
28  * either expressed or implied, of the Shogun Development Team.
29  *
30  * Code adapted from
31  * http://hannes.nickisch.org/code/approxXX.tar.gz
32  * and Gaussian Process Machine Learning Toolbox
33  * http://www.gaussianprocess.org/gpml/code/matlab/doc/
34  * and the reference paper is
35  * Challis, Edward, and David Barber.
36  * "Concave Gaussian variational approximations for inference in large-scale Bayesian linear models."
37  * International conference on Artificial Intelligence and Statistics. 2011.
38  *
39  * This code specifically adapted from function in approxKL.m and infKL.m
40  */
41 
43 
44 #ifdef HAVE_EIGEN3
49 
50 using namespace Eigen;
51 
52 namespace shogun
53 {
54 
55 CKLCholeskyInferenceMethod::CKLCholeskyInferenceMethod() : CKLLowerTriangularInferenceMethod()
56 {
57  init();
58 }
59 
61  CFeatures* feat, CMeanFunction* m, CLabels* lab, CLikelihoodModel* mod)
62  : CKLLowerTriangularInferenceMethod(kern, feat, m, lab, mod)
63 {
64  init();
65 }
66 
67 void CKLCholeskyInferenceMethod::init()
68 {
69  SG_ADD(&m_C, "C",
70  "The Cholesky represention of the variational co-variance matrix",
72  SG_ADD(&m_InvK_C, "invK_C",
73  " The K^{-1}C matrix",
75 }
76 
78  CInferenceMethod* inference)
79 {
80  if (inference==NULL)
81  return NULL;
82 
83  if (inference->get_inference_type()!=INF_KL_CHOLESKY)
84  SG_SERROR("Provided inference is not of type CKLCholeskyInferenceMethod!\n")
85 
86  SG_REF(inference);
87  return (CKLCholeskyInferenceMethod*)inference;
88 }
89 
91 {
100  update();
101 
102  index_t len=m_mu.vlen;
103  SGVector<float64_t> result(len);
104 
105  Map<VectorXd> eigen_result(result.vector, len);
106  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
107 
108  eigen_result=eigen_alpha;
109 
110  return result;
111 }
112 
114 {
115 }
116 
118 {
119  index_t len=m_mean_vec.vlen;
122  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
123 
124  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
125  //mu=K*alpha+m
126  eigen_mu=eigen_K*CMath::exp(m_log_scale*2.0)*eigen_alpha+eigen_mean;
127 
128  update_C();
129  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
130  Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen);
131  //s2=sum(C.*C,2);
132  eigen_s2=(eigen_C.array()*eigen_C.array()).rowwise().sum().matrix();
133 
135  bool status = lik->set_variational_distribution(m_mu, m_s2, m_labels);
136  if (status)
137  {
138  Map<MatrixXd> eigen_InvK_C(m_InvK_C.matrix, m_InvK_C.num_rows, m_InvK_C.num_cols);
139  eigen_InvK_C=solve_inverse(eigen_C);
140  }
141  return status;
142 }
143 
145 {
146  REQUIRE(gradient.vlen==m_alpha.vlen,
147  "The length of gradients (%d) should the same as the length of parameters (%d)\n",
148  gradient.vlen, m_alpha.vlen);
149 
151  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
152 
153  index_t len=m_mu.vlen;
154  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
155  Map<VectorXd> eigen_C_seq(m_alpha.vector+len, m_alpha.vlen-len);
156 
158  //[a,df,dV] = a_related2(mu,s2,y,lik);
159  TParameter* s2_param=lik->m_parameters->get_parameter("sigma2");
161  Map<VectorXd> eigen_dv(dv.vector, dv.vlen);
162 
163  TParameter* mu_param=lik->m_parameters->get_parameter("mu");
165  Map<VectorXd> eigen_df(df.vector, df.vlen);
166 
167  Map<VectorXd> eigen_dnlz_alpha(gradient.vector, len);
168  //dnlZ_alpha = -K*(df-alpha);
169  eigen_dnlz_alpha=eigen_K*CMath::exp(m_log_scale*2.0)*(-eigen_df+eigen_alpha);
170 
171  Map<VectorXd> eigen_dnlz_C_seq(gradient.vector+len, gradient.vlen-len);
172 
173  SGVector<float64_t> tmp(eigen_dnlz_C_seq.rows());
174  Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen);
175 
176  //dnlZ_C=low_matrix_to_vector(invK_C)-convert_diag(1.0./diag(C))-2*(alla(n+1:end,1).*convert_dC(dv));
177  float64_t offset=0;
178  for (index_t i=0; i<len; i++)
179  {
180  eigen_tmp.block(offset, 0, len-i, 1)=VectorXd::Map(eigen_dv.data()+i, len-i);
181  offset+=(len-i);
182  }
183 
184  //-2*(alla(n+1:end,1).*convert_dC(dV))
185  eigen_dnlz_C_seq=(-2.0*(eigen_C_seq.array()*eigen_tmp.array())).matrix();
186  //low_matrix_to_vector(invK_C)
187  get_lower_triangular_vector(m_InvK_C, tmp);
188  eigen_dnlz_C_seq+=eigen_tmp;
189 
190  Map<VectorXd> eigen_tmp2(tmp.vector, eigen_C.rows());
191  //-convert_diag(1.0./diag(C))
192  eigen_tmp2=(1.0/eigen_C.diagonal().array()).matrix();
193 
194  offset=0;
195  for (index_t i=0; i<len; i++)
196  {
197  eigen_dnlz_C_seq.block(offset,0,1,1)-=VectorXd::Map(eigen_tmp2.data()+i,1);
198  offset+=(len-i);
199  }
200 }
201 
203 {
204  Map<VectorXd> eigen_alpha(m_alpha.vector, m_mu.vlen);
205  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
207  //get mean vector and create eigen representation of it
209 
210  Map<MatrixXd> eigen_InvK_C(m_InvK_C.matrix, m_InvK_C.num_rows, m_InvK_C.num_cols);
211  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
212 
215 
216  //float64_t log_det=2.0*log_det(eigen_C)-m_log_det_Kernel;
217  float64_t log_det=2.0*eigen_C.diagonal().array().abs().log().sum()-m_log_det_Kernel;
218  float64_t trace=(eigen_InvK_C.array()*eigen_C.array()).sum();
219 
220  //nlZ = -a -logdet(V*inv(K))/2 -n/2 +(alpha'*K*alpha)/2 +trace(V*inv(K))/2;
221  float64_t result=-a+0.5*(-eigen_K.rows()+eigen_alpha.dot(eigen_mu-eigen_mean)+trace-log_det);
222  return result;
223 }
224 
226 {
228 
229  float64_t nlml_new=0;
230  float64_t nlml_def=0;
231 
233  index_t total_len=len*(len+3);
234 
235  if (m_alpha.vlen*2 == total_len)
236  {
238 
239  SGVector<float64_t> s2_tmp(m_s2.vlen);
240  Map<VectorXd> eigen_s2(s2_tmp.vector, s2_tmp.vlen);
241  eigen_s2.fill(1.0);
245  MatrixXd inv_K=solve_inverse(MatrixXd::Identity(m_ktrtr.num_rows, m_ktrtr.num_cols));
246  float64_t trace=inv_K.diagonal().array().sum();
247  nlml_def=-a+0.5*(-eigen_K.rows()+trace+m_log_det_Kernel);
248 
249  if (nlml_new<=nlml_def)
251  }
252 
253  if (m_alpha.vlen*2 != total_len || nlml_def<nlml_new)
254  {
255  if(m_alpha.vlen*2 != total_len)
256  m_alpha = SGVector<float64_t>(total_len/2);
257  m_alpha.zero();
258  index_t offset=0;
259  index_t count=0;
260  //init
261  for (index_t i=0; i<m_alpha.vlen; i++)
262  {
263  if (i-len==offset)
264  {
265  m_alpha[i]=1.0;
266  offset+=(len-count);
267  count++;
268  }
269  }
270  m_InvK_C=SGMatrix<float64_t>(len, len);
271  m_C=SGMatrix<float64_t>(len, len);
272  m_C.zero();
275  }
276 
277  nlml_new=lbfgs_optimization();
278 }
279 
280 void CKLCholeskyInferenceMethod::update_C()
281 {
282  ASSERT(m_C.num_rows == m_C.num_cols);
283  index_t len=m_C.num_rows;
284  ASSERT(m_alpha.vlen*2 == len*(len+3));
285 
286  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
287  Map<VectorXd> eigen_C_seq(m_alpha.vector+len, m_alpha.vlen-len);
288 
289  index_t offset=0;
290  for (index_t i=0; i<len; i++)
291  {
292  eigen_C.block(i, i, len-i ,1)=VectorXd::Map(eigen_C_seq.data()+offset, len-i);
293  offset+=(len-i);
294  }
295 }
296 
297 void CKLCholeskyInferenceMethod::get_lower_triangular_vector(SGMatrix<float64_t> square_matrix,
298  SGVector<float64_t> target)
299 {
300  ASSERT(square_matrix.num_rows == square_matrix.num_cols);
301  index_t len=m_InvK_C.num_rows;
302  ASSERT(target.vlen*2 == len*(len+1));
303 
304  Map<MatrixXd> eigen_square_matrix(square_matrix.matrix, len, len);
305  Map<VectorXd> eigen_result(target.vector, target.vlen);
306 
307  index_t offset=0;
308  for (index_t i=0; i<len; i++)
309  {
310  eigen_result.block(offset, 0, len-i, 1)=eigen_square_matrix.block(i, i, len-i, 1);
311  offset+=(len-i);
312  }
313 }
314 
316 {
319  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
320  eigen_Sigma=eigen_C*(eigen_C.transpose());
321 }
322 
324 {
327  Map<MatrixXd> eigen_InvK_C(m_InvK_C.matrix, m_InvK_C.num_rows, m_InvK_C.num_cols);
328  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
329  eigen_InvK_Sigma=eigen_InvK_C*(eigen_C.transpose());
330 }
331 
332 } /* namespace shogun */
333 
334 #endif /* HAVE_EIGEN3 */
virtual bool set_variational_distribution(SGVector< float64_t > mu, SGVector< float64_t > s2, const CLabels *lab)
SGVector< float64_t > m_alpha
The Inference Method base class.
static CKLCholeskyInferenceMethod * obtain_from_generic(CInferenceMethod *inference)
virtual SGVector< float64_t > get_variational_first_derivative(const TParameter *param) const =0
int32_t index_t
Definition: common.h:62
The class Labels models labels, i.e. class assignments of objects.
Definition: Labels.h:43
virtual float64_t get_negative_log_marginal_likelihood_helper()
virtual int32_t get_num_labels() const =0
The variational Gaussian Likelihood base class. The variational distribution is Gaussian.
TParameter * get_parameter(int32_t idx)
Definition: SGMatrix.h:20
parameter struct
#define REQUIRE(x,...)
Definition: SGIO.h:206
Parameter * m_parameters
Definition: SGObject.h:378
index_t num_cols
Definition: SGMatrix.h:378
An abstract class of the mean function.
Definition: MeanFunction.h:49
virtual SGVector< float64_t > get_alpha()
#define SG_REF(x)
Definition: SGObject.h:51
index_t num_rows
Definition: SGMatrix.h:376
virtual void get_gradient_of_nlml_wrt_parameters(SGVector< float64_t > gradient)
SGMatrix< float64_t > m_Sigma
The KL approximation inference method class.
index_t vlen
Definition: SGVector.h:494
#define ASSERT(x)
Definition: SGIO.h:201
virtual float64_t lbfgs_optimization()
double float64_t
Definition: common.h:50
static T sum(T *vec, int32_t len)
Return sum(vec)
Definition: SGVector.h:354
virtual SGVector< float64_t > get_variational_expection()=0
The KL approximation inference method class.
all of classes and functions are contained in the shogun namespace
Definition: class_list.h:18
The class Features is the base class of all feature objects.
Definition: Features.h:68
#define SG_SERROR(...)
Definition: SGIO.h:179
static float64_t exp(float64_t x)
Definition: Math.h:621
SGVector< float64_t > m_mu
SGVector< float64_t > m_s2
virtual EInferenceType get_inference_type() const
The Kernel base class.
Definition: Kernel.h:158
virtual CVariationalGaussianLikelihood * get_variational_likelihood() const
#define SG_ADD(...)
Definition: SGObject.h:81
virtual bool parameter_hash_changed()
Definition: SGObject.cpp:262
The Likelihood model base class.
SGMatrix< float64_t > m_ktrtr

SHOGUN Machine Learning Toolbox - Documentation