SHOGUN  4.0.0
KLDualInferenceMethod.cpp
浏览该文件的文档.
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  * Mohammad Emtiyaz Khan, Aleksandr Y. Aravkin, Michael P. Friedlander, Matthias Seeger
36  * Fast Dual Variational Inference for Non-Conjugate Latent Gaussian Models. ICML2013*
37  *
38  * This code specifically adapted from function in approxKL.m and infKL.m
39  */
40 
42 
43 #ifdef HAVE_EIGEN3
49 
50 using namespace Eigen;
51 
52 namespace shogun
53 {
54 
55 CKLDualInferenceMethod::CKLDualInferenceMethod() : 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 
68 {
70  update();
71 
73  return result;
74 }
75 
77 {
78 }
79 
81 {
83  REQUIRE(lik,
84  "The provided likelihood model is not a variational dual Likelihood model.\n");
85 }
86 
88 {
91 }
92 
94 {
97  return lik;
98 }
99 
100 void CKLDualInferenceMethod::init()
101 {
102  SG_ADD(&m_W, "W",
103  "noise matrix W",
105  SG_ADD(&m_sW, "sW",
106  "Square root of noise matrix W",
108  SG_ADD(&m_dv, "dv",
109  "the gradient of the variational expection wrt sigma2",
111  SG_ADD(&m_df, "df",
112  "the gradient of the variational expection wrt mu",
114  SG_ADD(&m_is_dual_valid, "is_dual_valid",
115  "whether the lambda (m_W) is valid or not",
117  m_is_dual_valid=false;
118 }
119 
121 {
124  Map<VectorXd> eigen_W(m_W.vector, m_W.vlen);
125 
126  lik->set_dual_parameters(m_W, m_labels);
127  m_is_dual_valid=lik->dual_parameters_valid();
128 
129  if (!m_is_dual_valid)
130  return false;
131 
132  //construct alpha
134  Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
135  eigen_alpha=-eigen_alpha;
136 
137  Map<VectorXd> eigen_sW(m_sW.vector, m_sW.vlen);
138  eigen_sW=eigen_W.array().sqrt().matrix();
139 
142 
143  //solve L'*V=diag(sW)*K
144  Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols);
145  eigen_V=eigen_L.triangularView<Upper>().adjoint().solve(eigen_sW.asDiagonal()*eigen_K*CMath::sq(m_scale));
146  Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen);
147  //Sigma=inv(inv(K)+diag(W))=K-K*diag(sW)*inv(L)'*inv(L)*diag(sW)*K
148  //v=abs(diag(Sigma))
149  eigen_s2=(eigen_K.diagonal().array()*CMath::sq(m_scale)-(eigen_V.array().pow(2).colwise().sum().transpose())).abs().matrix();
150 
151  //construct mu
153  Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
154  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
155  //mu=K*alpha+m
156  eigen_mu=eigen_K*CMath::sq(m_scale)*eigen_alpha+eigen_mean;
157  return true;
158 }
159 
161 {
162  if (!m_is_dual_valid)
163  return CMath::INFTY;
164 
166  Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
167  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
168  Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
170 
172 
174  float64_t result=0.5*eigen_alpha.dot(eigen_mu-eigen_mean)+a;
175  result+=eigen_mean.dot(eigen_alpha);
176  result-=eigen_L.diagonal().array().log().sum();
177 
178  return result;
179 }
180 
182 {
183  REQUIRE(gradient.vlen==m_alpha.vlen,
184  "The length of gradients (%d) should the same as the length of parameters (%d)\n",
185  gradient.vlen, m_alpha.vlen);
186 
187  if (!m_is_dual_valid)
188  return;
189 
190  Map<VectorXd> eigen_gradient(gradient.vector, gradient.vlen);
191 
193 
194  TParameter* lambda_param=lik->m_parameters->get_parameter("lambda");
195  SGVector<float64_t>d_lambda=lik->get_dual_first_derivative(lambda_param);
196  Map<VectorXd> eigen_d_lambda(d_lambda.vector, d_lambda.vlen);
197 
198  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
199  Map<VectorXd> eigen_s2(m_s2.vector, m_s2.vlen);
200 
201  eigen_gradient=-eigen_mu-0.5*eigen_s2+eigen_d_lambda;
202 }
203 
204 float64_t CKLDualInferenceMethod::get_nlml_wrapper(SGVector<float64_t> alpha, SGVector<float64_t> mu, SGMatrix<float64_t> L)
205 {
206  Map<MatrixXd> eigen_L(L.matrix, L.num_rows, L.num_cols);
207  Map<VectorXd> eigen_alpha(alpha.vector, alpha.vlen);
209  //get mean vector and create eigen representation of it
211  Map<VectorXd> eigen_mu(mu.vector, mu.vlen);
212  Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
213 
215 
216  SGVector<float64_t>lab=((CBinaryLabels*)m_labels)->get_labels();
217  Map<VectorXd> eigen_lab(lab.vector, lab.vlen);
218 
220 
221  float64_t trace=0;
222  //L_inv=L\eye(n);
223  //trace(L_inv'*L_inv) %V*inv(K)
224  MatrixXd eigen_t=eigen_L.triangularView<Upper>().adjoint().solve(MatrixXd::Identity(eigen_L.rows(),eigen_L.cols()));
225 
226  for(index_t idx=0; idx<eigen_t.rows(); idx++)
227  trace +=(eigen_t.col(idx).array().pow(2)).sum();
228 
229  //nlZ = -a -logdet(V*inv(K))/2 -n/2 +(alpha'*K*alpha)/2 +trace(V*inv(K))/2;
230  float64_t result=-a+eigen_L.diagonal().array().log().sum();
231 
232  result+=0.5*(-eigen_K.rows()+eigen_alpha.dot(eigen_mu-eigen_mean)+trace);
233  return result;
234 }
235 
237 {
239  bool status = lik->set_variational_distribution(m_mu, m_s2, m_labels);
240  if (status)
241  return get_nlml_wrapper(m_alpha, m_mu, m_L);
242  return CMath::NOT_A_NUMBER;
243 }
244 
246 {
248  Map<VectorXd> eigen_W(m_W.vector, m_W.vlen);
250  Map<VectorXd> eigen_sW(m_sW.vector, m_sW.vlen);
252  Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
253 
254  Map<VectorXd> eigen_dv(m_dv.vector, m_dv.vlen);
255  Map<VectorXd> eigen_df(m_df.vector, m_df.vlen);
256 
257  index_t len=m_W.vlen;
258  //U=inv(L')*diag(sW)
259  MatrixXd eigen_U=eigen_L.triangularView<Upper>().adjoint().solve(MatrixXd(eigen_sW.asDiagonal()));
260  //A=I-K*diag(sW)*inv(L)*inv(L')*diag(sW)
261  Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols);
262  MatrixXd eigen_A=MatrixXd::Identity(len, len)-eigen_V.transpose()*eigen_U;
263 
264  //AdK = A*dK;
265  MatrixXd AdK=eigen_A*eigen_dK;
266 
267  //z = diag(AdK) + sum(A.*AdK,2) - sum(A'.*AdK,1)';
268  VectorXd z=AdK.diagonal()+(eigen_A.array()*AdK.array()).rowwise().sum().matrix()
269  -(eigen_A.transpose().array()*AdK.array()).colwise().sum().transpose().matrix();
270 
271  float64_t result=eigen_alpha.dot(eigen_dK*(eigen_alpha/2.0-eigen_df))-z.dot(eigen_dv);
272 
273  return result;
274 }
275 
277 {
278  float64_t nlml_new=0;
279  float64_t nlml_def=0;
280 
283 
285  {
288  SGVector<float64_t> W_tmp(len);
289  Map<VectorXd> eigen_W(W_tmp.vector, W_tmp.vlen);
290  eigen_W.fill(0.5);
291  SGVector<float64_t> sW_tmp(len);
292  Map<VectorXd> eigen_sW(sW_tmp.vector, sW_tmp.vlen);
293  eigen_sW=eigen_W.array().sqrt().matrix();
295  Map<MatrixXd> eigen_L(L_tmp.matrix, L_tmp.num_rows, L_tmp.num_cols);
296 
297  lik->set_dual_parameters(W_tmp, m_labels);
298 
299  //construct alpha
301  Map<VectorXd> eigen_alpha(alpha_tmp.vector, alpha_tmp.vlen);
302  eigen_alpha=-eigen_alpha;
303  //construct mu
305  Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
306  SGVector<float64_t> mu_tmp(len);
307  Map<VectorXd> eigen_mu(mu_tmp.vector, mu_tmp.vlen);
308  //mu=K*alpha+m
309  eigen_mu=eigen_K*CMath::sq(m_scale)*eigen_alpha+eigen_mean;
310  //construct s2
311  MatrixXd eigen_V=eigen_L.triangularView<Upper>().adjoint().solve(eigen_sW.asDiagonal()*eigen_K*CMath::sq(m_scale));
312  SGVector<float64_t> s2_tmp(len);
313  Map<VectorXd> eigen_s2(s2_tmp.vector, s2_tmp.vlen);
314  eigen_s2=(eigen_K.diagonal().array()*CMath::sq(m_scale)-(eigen_V.array().pow(2).colwise().sum().transpose())).abs().matrix();
315 
316  lik->set_variational_distribution(mu_tmp, s2_tmp, m_labels);
317 
318  nlml_def=get_nlml_wrapper(alpha_tmp, mu_tmp, L_tmp);
319 
320  if (nlml_new<=nlml_def)
321  {
322  lik->set_dual_parameters(m_W, m_labels);
324  }
325  }
326 
327  if (m_alpha.vlen != m_labels->get_num_labels() || nlml_def<nlml_new)
328  {
331 
332  index_t len=m_alpha.vlen;
333 
334  m_W=SGVector<float64_t>(len);
335  for (index_t i=0; i<m_W.vlen; i++)
336  m_W[i]=0.5;
337 
338  lik->set_dual_parameters(m_W, m_labels);
339  m_sW=SGVector<float64_t>(len);
342  m_Sigma=SGMatrix<float64_t>(len, len);
343  m_V=SGMatrix<float64_t>(len, len);
344  }
345 
346  nlml_new=lbfgs_optimization();
348  TParameter* s2_param=lik->m_parameters->get_parameter("sigma2");
349  m_dv=lik->get_variational_first_derivative(s2_param);
350  TParameter* mu_param=lik->m_parameters->get_parameter("mu");
351  m_df=lik->get_variational_first_derivative(mu_param);
352 }
353 
354 float64_t CKLDualInferenceMethod::adjust_step(void *obj,
355  const float64_t *parameters, const float64_t *direction,
356  const int dim, const float64_t step)
357 {
358  /* Note that parameters = parameters_pre_iter - step * gradient_pre_iter */
359  CKLDualInferenceMethod * obj_prt
360  = static_cast<CKLDualInferenceMethod *>(obj);
361 
362  ASSERT(obj_prt != NULL);
363 
364  float64_t *non_const_direction=const_cast<float64_t *>(direction);
365  SGVector<float64_t> sg_direction(non_const_direction, dim, false);
366 
368 
369  float64_t adjust_stp=lik->adjust_step_wrt_dual_parameter(sg_direction, step);
370  return adjust_stp;
371 }
372 
373 float64_t CKLDualInferenceMethod::evaluate(void *obj, const float64_t *parameters,
374  float64_t *gradient, const int dim, const float64_t step)
375 {
376  /* Note that parameters = parameters_pre_iter - step * gradient_pre_iter */
377  CKLDualInferenceMethod * obj_prt
378  = static_cast<CKLDualInferenceMethod *>(obj);
379 
380  ASSERT(obj_prt != NULL);
381 
382  bool status=obj_prt->lbfgs_precompute();
383  if (status)
384  {
385  float64_t nlml=obj_prt->get_dual_objective_wrt_parameters();
386 
387  SGVector<float64_t> sg_gradient(gradient, dim, false);
388  Map<VectorXd> eigen_g(sg_gradient.vector, sg_gradient.vlen);
389  obj_prt->get_gradient_of_dual_objective_wrt_parameters(sg_gradient);
390 
391  return nlml;
392  }
393  return CMath::NOT_A_NUMBER;
394 }
395 
397 {
398  lbfgs_parameter_t lbfgs_param;
399  lbfgs_param.m = m_m;
400  lbfgs_param.max_linesearch = m_max_linesearch;
401  lbfgs_param.linesearch = m_linesearch;
402  lbfgs_param.max_iterations = m_max_iterations;
403  lbfgs_param.delta = m_delta;
404  lbfgs_param.past = m_past;
405  lbfgs_param.epsilon = m_epsilon;
406  lbfgs_param.min_step = m_min_step;
407  lbfgs_param.max_step = m_max_step;
408  lbfgs_param.ftol = m_ftol;
409  lbfgs_param.wolfe = m_wolfe;
410  lbfgs_param.gtol = m_gtol;
411  lbfgs_param.xtol = m_xtol;
412  lbfgs_param.orthantwise_c = m_orthantwise_c;
414  lbfgs_param.orthantwise_end = m_orthantwise_end;
415 
416  float64_t nlml_opt=0;
417  void * obj_prt = static_cast<void *>(this);
418 
419  Map<VectorXd> eigen_W(m_W.vector, m_W.vlen);
420  lbfgs(m_W.vlen, m_W.vector, &nlml_opt,
421  CKLDualInferenceMethod::evaluate,
422  NULL, obj_prt, &lbfgs_param, CKLDualInferenceMethod::adjust_step);
423  return nlml_opt;
424 }
425 
427 {
429  update();
430 
431  return SGVector<float64_t>(m_sW);
432 }
433 
435 {
436  /* get_derivative_related_cov(MatrixXd eigen_dK) does the similar job
437  * Therefore, this function body is empty
438  */
439 }
440 
442 {
443  /* L is automatically updated when update_alpha is called
444  * Therefore, this function body is empty
445  */
446 }
447 
449 {
451 }
452 
453 } /* namespace shogun */
454 
455 #endif /* HAVE_EIGEN3 */
virtual CDualVariationalGaussianLikelihood * get_dual_variational_likelihood() const
SGVector< float64_t > m_alpha
int32_t lbfgs(int32_t n, float64_t *x, float64_t *ptr_fx, lbfgs_evaluate_t proc_evaluate, lbfgs_progress_t proc_progress, void *instance, lbfgs_parameter_t *_param, lbfgs_adjust_step_t proc_adjust_step)
Definition: lbfgs.cpp:208
virtual void set_dual_parameters(SGVector< float64_t > the_lambda, const CLabels *lab)
static SGMatrix< float64_t > get_choleksy(SGVector< float64_t > W, SGVector< float64_t > sW, SGMatrix< float64_t > kernel, float64_t scale)
virtual SGVector< float64_t > get_mu_dual_parameter() 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
static const float64_t INFTY
infinity
Definition: Math.h:2048
virtual int32_t get_num_labels() const =0
static T sum(T *vec, int32_t len)
Return sum(vec)
Definition: SGVector.h:341
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)
static T sq(T x)
Definition: Math.h:450
TParameter * get_parameter(int32_t idx)
Definition: Parameter.h:286
float64_t orthantwise_c
Definition: lbfgs.h:311
Definition: SGMatrix.h:20
parameter struct
Definition: Parameter.h:32
virtual SGVector< float64_t > get_dual_objective_value()=0
#define REQUIRE(x,...)
Definition: SGIO.h:206
Parameter * m_parameters
Definition: SGObject.h:505
virtual SGVector< float64_t > get_mean_vector(const CFeatures *features) const =0
An abstract class of the mean function.
Definition: MeanFunction.h:28
virtual float64_t adjust_step_wrt_dual_parameter(SGVector< float64_t > direction, const float64_t step) const
SGMatrix< float64_t > m_Sigma
virtual void check_dual_inference(CLikelihoodModel *mod) const
The dual KL approximation inference method class.
SGMatrix< float64_t > m_L
#define ASSERT(x)
Definition: SGIO.h:201
void set_model(CLikelihoodModel *mod)
virtual void get_gradient_of_dual_objective_wrt_parameters(SGVector< float64_t > gradient)
virtual SGVector< float64_t > get_alpha()
virtual float64_t get_derivative_related_cov(Eigen::MatrixXd eigen_dK)
double float64_t
Definition: common.h:50
Matrix::Scalar sum(Matrix m, bool no_diag=false)
Definition: Redux.h:70
virtual bool set_variational_distribution(SGVector< float64_t > mu, SGVector< float64_t > s2, const CLabels *lab)
index_t num_rows
Definition: SGMatrix.h:329
virtual SGVector< float64_t > get_dual_first_derivative(const TParameter *param) const =0
Matrix< float64_t,-1,-1, 0,-1,-1 > MatrixXd
index_t num_cols
Definition: SGMatrix.h:331
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
SGVector< float64_t > m_mu
SGVector< float64_t > m_s2
The Kernel base class.
Definition: Kernel.h:153
Binary Labels for binary classification.
Definition: BinaryLabels.h:37
#define SG_ADD(...)
Definition: SGObject.h:81
virtual float64_t get_dual_objective_wrt_parameters()
virtual float64_t get_negative_log_marginal_likelihood_helper()
virtual SGVector< float64_t > get_diagonal_vector()
virtual SGVector< float64_t > get_variational_first_derivative(const TParameter *param) const
virtual void set_model(CLikelihoodModel *mod)
virtual bool parameter_hash_changed()
Definition: SGObject.cpp:263
Class that models dual variational likelihood.
The Likelihood model base class.
SGMatrix< float64_t > m_ktrtr
static const float64_t NOT_A_NUMBER
not a number
Definition: Math.h:2046
CLikelihoodModel * m_model
index_t vlen
Definition: SGVector.h:481

SHOGUN 机器学习工具包 - 项目文档