SHOGUN  4.0.0
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 
77 
79 {
88  update();
89 
90  index_t len=m_mu.vlen;
91  SGVector<float64_t> result(len);
92 
93  Map<VectorXd> eigen_result(result.vector, len);
94  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
95 
96  eigen_result=eigen_alpha;
97 
98  return result;
99 }
100 
102 {
103 }
104 
106 {
107  index_t len=m_mean_vec.vlen;
110  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
111 
112  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
113  //mu=K*alpha+m
114  eigen_mu=eigen_K*CMath::sq(m_scale)*eigen_alpha+eigen_mean;
115 
116  update_C();
117  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
118  Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen);
119  //s2=sum(C.*C,2);
120  eigen_s2=(eigen_C.array()*eigen_C.array()).rowwise().sum().matrix();
121 
123  bool status = lik->set_variational_distribution(m_mu, m_s2, m_labels);
124  if (status)
125  {
126  Map<MatrixXd> eigen_InvK_C(m_InvK_C.matrix, m_InvK_C.num_rows, m_InvK_C.num_cols);
127  eigen_InvK_C=solve_inverse(eigen_C);
128  }
129  return status;
130 }
131 
133 {
134  REQUIRE(gradient.vlen==m_alpha.vlen,
135  "The length of gradients (%d) should the same as the length of parameters (%d)\n",
136  gradient.vlen, m_alpha.vlen);
137 
139  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
140 
141  index_t len=m_mu.vlen;
142  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
143  Map<VectorXd> eigen_C_seq(m_alpha.vector+len, m_alpha.vlen-len);
144 
146  //[a,df,dV] = a_related2(mu,s2,y,lik);
147  TParameter* s2_param=lik->m_parameters->get_parameter("sigma2");
149  Map<VectorXd> eigen_dv(dv.vector, dv.vlen);
150 
151  TParameter* mu_param=lik->m_parameters->get_parameter("mu");
153  Map<VectorXd> eigen_df(df.vector, df.vlen);
154 
155  Map<VectorXd> eigen_dnlz_alpha(gradient.vector, len);
156  //dnlZ_alpha = -K*(df-alpha);
157  eigen_dnlz_alpha=eigen_K*CMath::sq(m_scale)*(-eigen_df+eigen_alpha);
158 
159  Map<VectorXd> eigen_dnlz_C_seq(gradient.vector+len, gradient.vlen-len);
160 
161  SGVector<float64_t> tmp(eigen_dnlz_C_seq.rows());
162  Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen);
163 
164  //dnlZ_C=low_matrix_to_vector(invK_C)-convert_diag(1.0./diag(C))-2*(alla(n+1:end,1).*convert_dC(dv));
165  float64_t offset=0;
166  for (index_t i=0; i<len; i++)
167  {
168  eigen_tmp.block(offset, 0, len-i, 1)=VectorXd::Map(eigen_dv.data()+i, len-i);
169  offset+=(len-i);
170  }
171 
172  //-2*(alla(n+1:end,1).*convert_dC(dV))
173  eigen_dnlz_C_seq=(-2.0*(eigen_C_seq.array()*eigen_tmp.array())).matrix();
174  //low_matrix_to_vector(invK_C)
175  get_lower_triangular_vector(m_InvK_C, tmp);
176  eigen_dnlz_C_seq+=eigen_tmp;
177 
178  Map<VectorXd> eigen_tmp2(tmp.vector, eigen_C.rows());
179  //-convert_diag(1.0./diag(C))
180  eigen_tmp2=(1.0/eigen_C.diagonal().array()).matrix();
181 
182  offset=0;
183  for (index_t i=0; i<len; i++)
184  {
185  eigen_dnlz_C_seq.block(offset,0,1,1)-=VectorXd::Map(eigen_tmp2.data()+i,1);
186  offset+=(len-i);
187  }
188 }
189 
191 {
192  Map<VectorXd> eigen_alpha(m_alpha.vector, m_mu.vlen);
193  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
195  //get mean vector and create eigen representation of it
197 
198  Map<MatrixXd> eigen_InvK_C(m_InvK_C.matrix, m_InvK_C.num_rows, m_InvK_C.num_cols);
199  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
200 
203 
204  //float64_t log_det=2.0*log_det(eigen_C)-m_log_det_Kernel;
205  float64_t log_det=2.0*eigen_C.diagonal().array().abs().log().sum()-m_log_det_Kernel;
206  float64_t trace=(eigen_InvK_C.array()*eigen_C.array()).sum();
207 
208  //nlZ = -a -logdet(V*inv(K))/2 -n/2 +(alpha'*K*alpha)/2 +trace(V*inv(K))/2;
209  float64_t result=-a+0.5*(-eigen_K.rows()+eigen_alpha.dot(eigen_mu-eigen_mean)+trace-log_det);
210  return result;
211 }
212 
214 {
216 
217  float64_t nlml_new=0;
218  float64_t nlml_def=0;
219 
221  index_t total_len=len*(len+3);
222 
223  if (m_alpha.vlen*2 == total_len)
224  {
226 
227  SGVector<float64_t> s2_tmp(m_s2.vlen);
228  Map<VectorXd> eigen_s2(s2_tmp.vector, s2_tmp.vlen);
229  eigen_s2.fill(1.0);
233  MatrixXd inv_K=solve_inverse(MatrixXd::Identity(m_ktrtr.num_rows, m_ktrtr.num_cols));
234  float64_t trace=inv_K.diagonal().array().sum();
235  nlml_def=-a+0.5*(-eigen_K.rows()+trace+m_log_det_Kernel);
236 
237  if (nlml_new<=nlml_def)
239  }
240 
241  if (m_alpha.vlen*2 != total_len || nlml_def<nlml_new)
242  {
243  if(m_alpha.vlen*2 != total_len)
244  m_alpha = SGVector<float64_t>(total_len/2);
245  m_alpha.zero();
246  index_t offset=0;
247  index_t count=0;
248  //init
249  for (index_t i=0; i<m_alpha.vlen; i++)
250  {
251  if (i-len==offset)
252  {
253  m_alpha[i]=1.0;
254  offset+=(len-count);
255  count++;
256  }
257  }
258  m_InvK_C=SGMatrix<float64_t>(len, len);
259  m_C=SGMatrix<float64_t>(len, len);
260  m_C.zero();
263  }
264 
265  nlml_new=lbfgs_optimization();
266 }
267 
268 void CKLCholeskyInferenceMethod::update_C()
269 {
270  ASSERT(m_C.num_rows == m_C.num_cols);
271  index_t len=m_C.num_rows;
272  ASSERT(m_alpha.vlen*2 == len*(len+3));
273 
274  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
275  Map<VectorXd> eigen_C_seq(m_alpha.vector+len, m_alpha.vlen-len);
276 
277  index_t offset=0;
278  for (index_t i=0; i<len; i++)
279  {
280  eigen_C.block(i, i, len-i ,1)=VectorXd::Map(eigen_C_seq.data()+offset, len-i);
281  offset+=(len-i);
282  }
283 }
284 
285 void CKLCholeskyInferenceMethod::get_lower_triangular_vector(SGMatrix<float64_t> square_matrix,
286  SGVector<float64_t> target)
287 {
288  ASSERT(square_matrix.num_rows == square_matrix.num_cols);
289  index_t len=m_InvK_C.num_rows;
290  ASSERT(target.vlen*2 == len*(len+1));
291 
292  Map<MatrixXd> eigen_square_matrix(square_matrix.matrix, len, len);
293  Map<VectorXd> eigen_result(target.vector, target.vlen);
294 
295  index_t offset=0;
296  for (index_t i=0; i<len; i++)
297  {
298  eigen_result.block(offset, 0, len-i, 1)=eigen_square_matrix.block(i, i, len-i, 1);
299  offset+=(len-i);
300  }
301 }
302 
304 {
307  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
308  eigen_Sigma=eigen_C*(eigen_C.transpose());
309 }
310 
312 {
315  Map<MatrixXd> eigen_InvK_C(m_InvK_C.matrix, m_InvK_C.num_rows, m_InvK_C.num_cols);
316  Map<MatrixXd> eigen_C(m_C.matrix, m_C.num_rows, m_C.num_cols);
317  eigen_InvK_Sigma=eigen_InvK_C*(eigen_C.transpose());
318 }
319 
320 } /* namespace shogun */
321 
322 #endif /* HAVE_EIGEN3 */
virtual bool set_variational_distribution(SGVector< float64_t > mu, SGVector< float64_t > s2, const CLabels *lab)
SGVector< float64_t > m_alpha
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
static T sum(T *vec, int32_t len)
Return sum(vec)
Definition: SGVector.h:341
The variational Gaussian Likelihood base class. The variational distribution is Gaussian.
static T sq(T x)
Definition: Math.h:450
TParameter * get_parameter(int32_t idx)
Definition: Parameter.h:286
Definition: SGMatrix.h:20
parameter struct
Definition: Parameter.h:32
#define REQUIRE(x,...)
Definition: SGIO.h:206
Parameter * m_parameters
Definition: SGObject.h:505
An abstract class of the mean function.
Definition: MeanFunction.h:28
virtual SGVector< float64_t > get_alpha()
virtual void get_gradient_of_nlml_wrt_parameters(SGVector< float64_t > gradient)
SGMatrix< float64_t > m_Sigma
The KL approximation inference method class.
#define ASSERT(x)
Definition: SGIO.h:201
virtual float64_t lbfgs_optimization()
double float64_t
Definition: common.h:50
Matrix::Scalar sum(Matrix m, bool no_diag=false)
Definition: Redux.h:70
index_t num_rows
Definition: SGMatrix.h:329
virtual SGVector< float64_t > get_variational_expection()=0
index_t num_cols
Definition: SGMatrix.h:331
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
SGVector< float64_t > m_mu
SGVector< float64_t > m_s2
The Kernel base class.
Definition: Kernel.h:153
virtual CVariationalGaussianLikelihood * get_variational_likelihood() const
#define SG_ADD(...)
Definition: SGObject.h:81
virtual bool parameter_hash_changed()
Definition: SGObject.cpp:263
The Likelihood model base class.
SGMatrix< float64_t > m_ktrtr
index_t vlen
Definition: SGVector.h:481

SHOGUN Machine Learning Toolbox - Documentation