SHOGUN  4.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
KLCovarianceInferenceMethod.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  * Nickisch, Hannes, and Carl Edward Rasmussen.
36  * "Approximations for Binary Gaussian Process Classification."
37  * Journal of Machine Learning Research 9.10 (2008).
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 CKLCovarianceInferenceMethod::CKLCovarianceInferenceMethod() : CKLInferenceMethod()
56 {
57  init();
58 }
59 
61  CFeatures* feat, CMeanFunction* m, CLabels* lab, CLikelihoodModel* mod)
62  : CKLInferenceMethod(kern, feat, m, lab, mod)
63 {
64  init();
65 }
66 
67 void CKLCovarianceInferenceMethod::init()
68 {
69  SG_ADD(&m_V, "V",
70  "V is L'*V=diag(sW)*K",
72  SG_ADD(&m_A, "A",
73  "A is A=I-K*diag(sW)*inv(L)'*inv(L)*diag(sW)",
75  SG_ADD(&m_W, "W",
76  "noise matrix W",
78  SG_ADD(&m_sW, "sW",
79  "Square root of noise matrix W",
81  SG_ADD(&m_dv, "dv",
82  "the gradient of the variational expection wrt sigma2",
84  SG_ADD(&m_df, "df",
85  "the gradient of the variational expection wrt mu",
87 }
88 
89 
91 {
100  update();
101 
102  index_t len=m_alpha.vlen/2;
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  CInferenceMethod* inference)
119 {
120  if (inference==NULL)
121  return NULL;
122 
123  if (inference->get_inference_type()!=INF_KL_COVARIANCE)
124  SG_SERROR("Provided inference is not of type CKLCovarianceInferenceMethod!\n")
125 
126  SG_REF(inference);
127  return (CKLCovarianceInferenceMethod*)inference;
128 }
129 
131 {
133  Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
134 
136 
137  index_t len=m_alpha.vlen/2;
138  //construct mu
139  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
140 
141  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
142  //mu=K*alpha+m
143  eigen_mu=eigen_K*CMath::exp(m_log_scale*2.0)*eigen_alpha+eigen_mean;
144 
145  //construct s2
146  Map<VectorXd> eigen_log_neg_lambda(m_alpha.vector+len, len);
147 
148  Map<VectorXd> eigen_W(m_W.vector, m_W.vlen);
149  eigen_W=(2.0*eigen_log_neg_lambda.array().exp()).matrix();
150 
151  Map<VectorXd> eigen_sW(m_sW.vector, m_sW.vlen);
152  eigen_sW=eigen_W.array().sqrt().matrix();
153 
156 
157  //solve L'*V=diag(sW)*K
158  Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols);
159  eigen_V=eigen_L.triangularView<Upper>().adjoint().solve(eigen_sW.asDiagonal()*eigen_K*CMath::exp(m_log_scale*2.0));
160  Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen);
161  //Sigma=inv(inv(K)-2*diag(lambda))=K-K*diag(sW)*inv(L)'*inv(L)*diag(sW)*K
162  //v=abs(diag(Sigma))
163  eigen_s2=(eigen_K.diagonal().array()*CMath::exp(m_log_scale*2.0)-(eigen_V.array().pow(2).colwise().sum().transpose())).abs().matrix();
164 
166  bool status = lik->set_variational_distribution(m_mu, m_s2, m_labels);
167  return status;
168 }
169 
171 {
172  REQUIRE(gradient.vlen==m_alpha.vlen,
173  "The length of gradients (%d) should the same as the length of parameters (%d)\n",
174  gradient.vlen, m_alpha.vlen);
175 
177  Map<VectorXd> eigen_sW(m_sW.vector, m_sW.vlen);
178  Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols);
180  Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen);
181 
182  index_t len=m_alpha.vlen/2;
183  Map<VectorXd> eigen_alpha(m_alpha.vector, len);
184  Map<VectorXd> eigen_log_neg_lambda(m_alpha.vector+len, len);
185 
188 
189  //[a,df,dV] = a_related2(mu,s2,y,lik);
190  TParameter* s2_param=lik->m_parameters->get_parameter("sigma2");
191  m_dv=lik->get_variational_first_derivative(s2_param);
192  Map<VectorXd> eigen_dv(m_dv.vector, m_dv.vlen);
193 
194  TParameter* mu_param=lik->m_parameters->get_parameter("mu");
195  m_df=lik->get_variational_first_derivative(mu_param);
196  Map<VectorXd> eigen_df(m_df.vector, m_df.vlen);
197  //U=inv(L')*diag(sW)
198  MatrixXd eigen_U=eigen_L.triangularView<Upper>().adjoint().solve(MatrixXd(eigen_sW.asDiagonal()));
199  Map<MatrixXd> eigen_A(m_A.matrix, m_A.num_rows, m_A.num_cols);
200  // A=I-K*diag(sW)*inv(L)*inv(L')*diag(sW)
201  eigen_A=MatrixXd::Identity(len, len)-eigen_V.transpose()*eigen_U;
202 
205 
206  Map<VectorXd> eigen_dnlz_alpha(gradient.vector, len);
207  Map<VectorXd> eigen_dnlz_log_neg_lambda(gradient.vector+len, len);
208 
209  //dlZ_alpha = K*(df-alpha);
210  eigen_dnlz_alpha=eigen_K*CMath::exp(m_log_scale*2.0)*(-eigen_df+eigen_alpha);
211 
212  //dlZ_lambda = 2*(Sigma.*Sigma)*dV +v -sum(Sigma.*A,2); % => fast diag(V*VinvK')
213  //dlZ_log_neg_lambda = dlZ_lambda .* lambda;
214  //dnlZ = -[dlZ_alpha; dlZ_log_neg_lambda];
215  eigen_dnlz_log_neg_lambda=(eigen_Sigma.array().pow(2)*2.0).matrix()*eigen_dv+eigen_s2;
216  eigen_dnlz_log_neg_lambda=eigen_dnlz_log_neg_lambda-(eigen_Sigma.array()*eigen_A.array()).rowwise().sum().matrix();
217  eigen_dnlz_log_neg_lambda=(eigen_log_neg_lambda.array().exp()*eigen_dnlz_log_neg_lambda.array()).matrix();
218 }
219 
220 
222 {
224  Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen/2);
225  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
227  //get mean vector and create eigen representation of it
229  Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
230 
233 
234  float64_t trace=0;
235  //L_inv=L\eye(n);
236  //trace(L_inv'*L_inv) %V*inv(K)
237  MatrixXd eigen_t=eigen_L.triangularView<Upper>().adjoint().solve(MatrixXd::Identity(eigen_L.rows(),eigen_L.cols()));
238 
239  for(index_t idx=0; idx<eigen_t.rows(); idx++)
240  trace +=(eigen_t.col(idx).array().pow(2)).sum();
241 
242  //nlZ = -a -logdet(V*inv(K))/2 -n/2 +(alpha'*K*alpha)/2 +trace(V*inv(K))/2;
243  float64_t result=-a+eigen_L.diagonal().array().log().sum();
244  result+=0.5*(-eigen_K.rows()+eigen_alpha.dot(eigen_mu-eigen_mean)+trace);
245  return result;
246 }
247 
249 {
250  Map<MatrixXd> eigen_dK(dK.matrix, dK.num_rows, dK.num_cols);
252  Map<VectorXd> eigen_W(m_W.vector, m_W.vlen);
254  Map<VectorXd> eigen_sW(m_sW.vector, m_sW.vlen);
256  Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen/2);
257  Map<MatrixXd> eigen_A(m_A.matrix, m_A.num_rows, m_A.num_cols);
258 
259  Map<VectorXd> eigen_dv(m_dv.vector, m_dv.vlen);
260  Map<VectorXd> eigen_df(m_df.vector, m_df.vlen);
261 
262  //AdK = A*dK;
263  MatrixXd AdK=eigen_A*eigen_dK;
264 
265  //z = diag(AdK) + sum(A.*AdK,2) - sum(A'.*AdK,1)';
266  VectorXd z=AdK.diagonal()+(eigen_A.array()*AdK.array()).rowwise().sum().matrix()
267  -(eigen_A.transpose().array()*AdK.array()).colwise().sum().transpose().matrix();
268 
269  //dnlZ(j) = alpha'*dK*(alpha/2-df) - z'*dv;
270  return eigen_alpha.dot(eigen_dK*(eigen_alpha/2.0-eigen_df))-z.dot(eigen_dv);
271 }
272 
274 {
275  float64_t nlml_new=0;
276  float64_t nlml_def=0;
277 
279 
280  if (m_alpha.vlen == m_labels->get_num_labels()*2)
281  {
283 
284  float64_t trace=0;
285  LLT<MatrixXd> llt((eigen_K*CMath::exp(m_log_scale*2.0))+
286  MatrixXd::Identity(eigen_K.rows(), eigen_K.cols()));
287  MatrixXd LL=llt.matrixU();
288  MatrixXd tt=LL.triangularView<Upper>().adjoint().solve(MatrixXd::Identity(LL.rows(),LL.cols()));
289 
290  for(index_t idx=0; idx<tt.rows(); idx++)
291  trace+=(tt.col(idx).array().pow(2)).sum();
292 
293  MatrixXd eigen_V=LL.triangularView<Upper>().adjoint().solve(eigen_K*CMath::exp(m_log_scale*2.0));
294  SGVector<float64_t> s2_tmp(m_s2.vlen);
295  Map<VectorXd> eigen_s2(s2_tmp.vector, s2_tmp.vlen);
296  eigen_s2=(eigen_K.diagonal().array()*CMath::exp(m_log_scale*2.0)-(eigen_V.array().pow(2).colwise().sum().transpose())).abs().matrix();
298 
300  lik->set_variational_distribution(mean, s2_tmp, m_labels);
302 
303  nlml_def=-a+LL.diagonal().array().log().sum();
304  nlml_def+=0.5*(-eigen_K.rows()+trace);
305 
306  if (nlml_new<=nlml_def)
308  }
309 
310  if (m_alpha.vlen != m_labels->get_num_labels()*2 || nlml_def<nlml_new)
311  {
312  if(m_alpha.vlen != m_labels->get_num_labels()*2)
314 
315  //init
316  for (index_t i=0; i<m_alpha.vlen; i++)
317  {
318  if (i<m_alpha.vlen/2)
319  m_alpha[i]=0;
320  else
321  m_alpha[i]=CMath::log(0.5);
322  }
323 
324  index_t len=m_alpha.vlen/2;
325  m_W=SGVector<float64_t>(len);
326  m_sW=SGVector<float64_t>(len);
329  m_V=SGMatrix<float64_t>(len, len);
330  m_Sigma=SGMatrix<float64_t>(len, len);
331  m_A=SGMatrix<float64_t>(len, len);
332  }
333 
334  nlml_new=lbfgs_optimization();
335 }
336 
338 {
340  update();
341 
342  return SGVector<float64_t>(m_sW);
343 }
344 
346 {
350 }
351 
353 {
357 }
358 
360 {
366 }
367 
368 } /* namespace shogun */
369 
370 #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.
virtual SGVector< float64_t > get_variational_first_derivative(const TParameter *param) const =0
static SGMatrix< float64_t > get_choleksy(SGVector< float64_t > W, SGVector< float64_t > sW, SGMatrix< float64_t > kernel, float64_t scale)
int32_t index_t
Definition: common.h:62
virtual void get_gradient_of_nlml_wrt_parameters(SGVector< float64_t > gradient)
The class Labels models labels, i.e. class assignments of objects.
Definition: Labels.h:43
virtual int32_t get_num_labels() const =0
virtual float64_t get_derivative_related_cov(SGMatrix< float64_t > dK)
The variational Gaussian Likelihood base class. The variational distribution is Gaussian.
static SGMatrix< float64_t > get_inverse(SGMatrix< float64_t > L, SGMatrix< float64_t > kernel, SGVector< float64_t > sW, SGMatrix< float64_t > V, float64_t scale)
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
virtual SGVector< float64_t > get_mean_vector(const CFeatures *features) const =0
static CKLCovarianceInferenceMethod * obtain_from_generic(CInferenceMethod *inference)
An abstract class of the mean function.
Definition: MeanFunction.h:49
#define SG_REF(x)
Definition: SGObject.h:51
index_t num_rows
Definition: SGMatrix.h:376
SGMatrix< float64_t > m_Sigma
index_t vlen
Definition: SGVector.h:494
SGMatrix< float64_t > m_L
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
Matrix< float64_t,-1,-1, 0,-1,-1 > MatrixXd
The KL approximation inference method class.
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
static float64_t log(float64_t v)
Definition: Math.h:922
virtual EInferenceType get_inference_type() const
virtual SGVector< float64_t > get_diagonal_vector()
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