SHOGUN  4.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
EPInferenceMethod.cpp
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * Written (W) 2013 Roman Votyakov
8  *
9  * Based on ideas from GAUSSIAN PROCESS REGRESSION AND CLASSIFICATION Toolbox
10  * Copyright (C) 2005-2013 by Carl Edward Rasmussen & Hannes Nickisch under the
11  * FreeBSD License
12  * http://www.gaussianprocess.org/gpml/code/matlab/doc/
13  */
14 
16 
17 #ifdef HAVE_EIGEN3
18 
24 
26 
27 using namespace shogun;
28 using namespace Eigen;
29 
30 // try to use previously allocated memory for SGVector
31 #define CREATE_SGVECTOR(vec, len, sg_type) \
32  { \
33  if (!vec.vector || vec.vlen!=len) \
34  vec=SGVector<sg_type>(len); \
35  }
36 
37 // try to use previously allocated memory for SGMatrix
38 #define CREATE_SGMATRIX(mat, rows, cols, sg_type) \
39  { \
40  if (!mat.matrix || mat.num_rows!=rows || mat.num_cols!=cols) \
41  mat=SGMatrix<sg_type>(rows, cols); \
42  }
43 
45 {
46  init();
47 }
48 
50  CMeanFunction* mean, CLabels* labels, CLikelihoodModel* model)
51  : CInferenceMethod(kernel, features, mean, labels, model)
52 {
53  init();
54 }
55 
57 {
58 }
59 
60 void CEPInferenceMethod::init()
61 {
62  m_max_sweep=15;
63  m_min_sweep=2;
64  m_tol=1e-4;
65 }
66 
68  CInferenceMethod* inference)
69 {
70  if (inference==NULL)
71  return NULL;
72 
73  if (inference->get_inference_type()!=INF_EP)
74  SG_SERROR("Provided inference is not of type CEPInferenceMethod!\n")
75 
76  SG_REF(inference);
77  return (CEPInferenceMethod*)inference;
78 }
79 
81 {
83  update();
84 
85  return m_nlZ;
86 }
87 
89 {
91  update();
92 
94 }
95 
97 {
99  update();
100 
101  return SGMatrix<float64_t>(m_L);
102 }
103 
105 {
107  update();
108 
109  return SGVector<float64_t>(m_sttau);
110 }
111 
113 {
115  update();
116 
117  return SGVector<float64_t>(m_mu);
118 }
119 
121 {
123  update();
124 
125  return SGMatrix<float64_t>(m_Sigma);
126 }
127 
129 {
130  SG_DEBUG("entering\n");
131 
132  // update kernel and feature matrix
134 
135  // get number of labels (trainig examples)
137 
138  // try to use tilde values from previous call
139  if (m_ttau.vlen==n)
140  {
141  update_chol();
145  }
146 
147  // get mean vector
149 
150  // get and scale diagonal of the kernel matrix
152  ktrtr_diag.scale(CMath::sq(m_scale));
153 
154  // marginal likelihood for ttau = tnu = 0
156  mean, ktrtr_diag, m_labels));
157 
158  // use zero values if we have no better guess or it's better
159  if (m_ttau.vlen!=n || m_nlZ>nlZ0)
160  {
161  CREATE_SGVECTOR(m_ttau, n, float64_t);
162  m_ttau.zero();
163 
164  CREATE_SGVECTOR(m_sttau, n, float64_t);
165  m_sttau.zero();
166 
167  CREATE_SGVECTOR(m_tnu, n, float64_t);
168  m_tnu.zero();
169 
171 
172  // copy data manually, since we don't have appropriate method
173  for (index_t i=0; i<m_ktrtr.num_rows; i++)
174  for (index_t j=0; j<m_ktrtr.num_cols; j++)
175  m_Sigma(i,j)=m_ktrtr(i,j)*CMath::sq(m_scale);
176 
177  CREATE_SGVECTOR(m_mu, n, float64_t);
178  m_mu.zero();
179 
180  // set marginal likelihood
181  m_nlZ=nlZ0;
182  }
183 
184  // create vector of the random permutation
185  SGVector<index_t> v(n);
186  v.range_fill();
187 
188  // cavity tau and nu vectors
189  SGVector<float64_t> tau_n(n);
190  SGVector<float64_t> nu_n(n);
191 
192  // cavity mu and s2 vectors
193  SGVector<float64_t> mu_n(n);
194  SGVector<float64_t> s2_n(n);
195 
196  float64_t nlZ_old=CMath::INFTY;
197  uint32_t sweep=0;
198 
199  while ((CMath::abs(m_nlZ-nlZ_old)>m_tol && sweep<m_max_sweep) ||
200  sweep<m_min_sweep)
201  {
202  nlZ_old=m_nlZ;
203  sweep++;
204 
205  // shuffle random permutation
206  CMath::permute(v);
207 
208  for (index_t j=0; j<n; j++)
209  {
210  index_t i=v[j];
211 
212  // find cavity paramters
213  tau_n[i]=1.0/m_Sigma(i,i)-m_ttau[i];
214  nu_n[i]=m_mu[i]/m_Sigma(i,i)+mean[i]*tau_n[i]-m_tnu[i];
215 
216  // compute cavity mean and variance
217  mu_n[i]=nu_n[i]/tau_n[i];
218  s2_n[i]=1.0/tau_n[i];
219 
220  // get moments
221  float64_t mu=m_model->get_first_moment(mu_n, s2_n, m_labels, i);
222  float64_t s2=m_model->get_second_moment(mu_n, s2_n, m_labels, i);
223 
224  // save old value of ttau
225  float64_t ttau_old=m_ttau[i];
226 
227  // compute ttau and sqrt(ttau)
228  m_ttau[i]=CMath::max(1.0/s2-tau_n[i], 0.0);
229  m_sttau[i]=CMath::sqrt(m_ttau[i]);
230 
231  // compute tnu
232  m_tnu[i]=mu/s2-nu_n[i];
233 
234  // compute difference ds2=ttau_new-ttau_old
235  float64_t ds2=m_ttau[i]-ttau_old;
236 
237  // create eigen representation of Sigma, tnu and mu
238  Map<MatrixXd> eigen_Sigma(m_Sigma.matrix, m_Sigma.num_rows,
239  m_Sigma.num_cols);
240  Map<VectorXd> eigen_tnu(m_tnu.vector, m_tnu.vlen);
241  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
242 
243  VectorXd eigen_si=eigen_Sigma.col(i);
244 
245  // rank-1 update Sigma
246  eigen_Sigma=eigen_Sigma-ds2/(1.0+ds2*eigen_si(i))*eigen_si*
247  eigen_si.adjoint();
248 
249  // update mu
250  eigen_mu=eigen_Sigma*eigen_tnu;
251  }
252 
253  // update upper triangular factor (L^T) of Cholesky decomposition of
254  // matrix B, approximate posterior covariance and mean, negative
255  // marginal likelihood
256  update_chol();
260  }
261 
262  if (sweep==m_max_sweep && CMath::abs(m_nlZ-nlZ_old)>m_tol)
263  {
264  SG_ERROR("Maximum number (%d) of sweeps reached, but tolerance (%f) was "
265  "not yet reached. You can manually set maximum number of sweeps "
266  "or tolerance to fix this problem.\n", m_max_sweep, m_tol);
267  }
268 
269  // update vector alpha
270  update_alpha();
271 
272  // update matrices to compute derivatives
273  update_deriv();
274 
275  // update hash of the parameters
277 
278  SG_DEBUG("leaving\n");
279 }
280 
282 {
283  // create eigen representations kernel matrix, L^T, sqrt(ttau) and tnu
284  Map<MatrixXd> eigen_K(m_ktrtr.matrix, m_ktrtr.num_rows, m_ktrtr.num_cols);
285  Map<VectorXd> eigen_tnu(m_tnu.vector, m_tnu.vlen);
286  Map<VectorXd> eigen_sttau(m_sttau.vector, m_sttau.vlen);
287  Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols);
288 
289  // create shogun and eigen representation of the alpha vector
291  Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
292 
293  // solve LL^T * v = tS^(1/2) * K * tnu
294  VectorXd eigen_v=eigen_L.triangularView<Upper>().adjoint().solve(
295  eigen_sttau.cwiseProduct(eigen_K*CMath::sq(m_scale)*eigen_tnu));
296  eigen_v=eigen_L.triangularView<Upper>().solve(eigen_v);
297 
298  // compute alpha = (I - tS^(1/2) * B^(-1) * tS(1/2) * K) * tnu =
299  // tnu - tS(1/2) * (L^T)^(-1) * L^(-1) * tS^(1/2) * K * tnu =
300  // tnu - tS(1/2) * v
301  eigen_alpha=eigen_tnu-eigen_sttau.cwiseProduct(eigen_v);
302 }
303 
305 {
306  // create eigen representations of kernel matrix and sqrt(ttau)
307  Map<MatrixXd> eigen_K(m_ktrtr.matrix, m_ktrtr.num_rows, m_ktrtr.num_cols);
308  Map<VectorXd> eigen_sttau(m_sttau.vector, m_sttau.vlen);
309 
310  // create shogun and eigen representation of the upper triangular factor
311  // (L^T) of the Cholesky decomposition of the matrix B
313  Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols);
314 
315  // compute upper triangular factor L^T of the Cholesky decomposion of the
316  // matrix: B = tS^(1/2) * K * tS^(1/2) + I
317  LLT<MatrixXd> eigen_chol((eigen_sttau*eigen_sttau.adjoint()).cwiseProduct(
318  eigen_K*CMath::sq(m_scale))+
319  MatrixXd::Identity(m_L.num_rows, m_L.num_cols));
320 
321  eigen_L=eigen_chol.matrixU();
322 }
323 
325 {
326  // create eigen representations of kernel matrix, L^T matrix and sqrt(ttau)
327  Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols);
328  Map<MatrixXd> eigen_K(m_ktrtr.matrix, m_ktrtr.num_rows, m_ktrtr.num_cols);
329  Map<VectorXd> eigen_sttau(m_sttau.vector, m_sttau.vlen);
330 
331  // create shogun and eigen representation of the approximate covariance
332  // matrix
334  Map<MatrixXd> eigen_Sigma(m_Sigma.matrix, m_Sigma.num_rows, m_Sigma.num_cols);
335 
336  // compute V = L^(-1) * tS^(1/2) * K, using upper triangular factor L^T
337  MatrixXd eigen_V=eigen_L.triangularView<Upper>().adjoint().solve(
338  eigen_sttau.asDiagonal()*eigen_K*CMath::sq(m_scale));
339 
340  // compute covariance matrix of the posterior:
341  // Sigma = K - K * tS^(1/2) * (L * L^T)^(-1) * tS^(1/2) * K =
342  // K - (K * tS^(1/2)) * (L^T)^(-1) * L^(-1) * tS^(1/2) * K =
343  // K - (tS^(1/2) * K)^T * (L^(-1))^T * L^(-1) * tS^(1/2) * K = K - V^T * V
344  eigen_Sigma=eigen_K*CMath::sq(m_scale)-eigen_V.adjoint()*eigen_V;
345 }
346 
348 {
349  // create eigen representation of posterior covariance matrix and tnu
350  Map<MatrixXd> eigen_Sigma(m_Sigma.matrix, m_Sigma.num_rows, m_Sigma.num_cols);
351  Map<VectorXd> eigen_tnu(m_tnu.vector, m_tnu.vlen);
352 
353  // create shogun and eigen representation of the approximate mean vector
354  CREATE_SGVECTOR(m_mu, m_tnu.vlen, float64_t);
355  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
356 
357  // compute mean vector of the approximate posterior: mu = Sigma * tnu
358  eigen_mu=eigen_Sigma*eigen_tnu;
359 }
360 
362 {
363  // create eigen representation of Sigma, L, mu, tnu, ttau
364  Map<MatrixXd> eigen_Sigma(m_Sigma.matrix, m_Sigma.num_rows, m_Sigma.num_cols);
365  Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols);
366  Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen);
367  Map<VectorXd> eigen_tnu(m_tnu.vector, m_tnu.vlen);
368  Map<VectorXd> eigen_ttau(m_ttau.vector, m_ttau.vlen);
369 
370  // get and create eigen representation of the mean vector
372  Map<VectorXd> eigen_m(m.vector, m.vlen);
373 
374  // compute vector of cavity parameter tau_n
375  VectorXd eigen_tau_n=(VectorXd::Ones(m_ttau.vlen)).cwiseQuotient(
376  eigen_Sigma.diagonal())-eigen_ttau;
377 
378  // compute vector of cavity parameter nu_n
379  VectorXd eigen_nu_n=eigen_mu.cwiseQuotient(eigen_Sigma.diagonal())-
380  eigen_tnu+eigen_m.cwiseProduct(eigen_tau_n);
381 
382  // compute cavity mean: mu_n=nu_n/tau_n
383  SGVector<float64_t> mu_n(m_ttau.vlen);
384  Map<VectorXd> eigen_mu_n(mu_n.vector, mu_n.vlen);
385 
386  eigen_mu_n=eigen_nu_n.cwiseQuotient(eigen_tau_n);
387 
388  // compute cavity variance: s2_n=1.0/tau_n
389  SGVector<float64_t> s2_n(m_ttau.vlen);
390  Map<VectorXd> eigen_s2_n(s2_n.vector, s2_n.vlen);
391 
392  eigen_s2_n=(VectorXd::Ones(m_ttau.vlen)).cwiseQuotient(eigen_tau_n);
393 
395  m_model->get_log_zeroth_moments(mu_n, s2_n, m_labels));
396 
397  // compute nlZ_part1=sum(log(diag(L)))-sum(lZ)-tnu'*Sigma*tnu/2
398  float64_t nlZ_part1=eigen_L.diagonal().array().log().sum()-lZ-
399  (eigen_tnu.adjoint()*eigen_Sigma).dot(eigen_tnu)/2.0;
400 
401  // compute nlZ_part2=sum(tnu.^2./(tau_n+ttau))/2-sum(log(1+ttau./tau_n))/2
402  float64_t nlZ_part2=(eigen_tnu.array().square()/
403  (eigen_tau_n+eigen_ttau).array()).sum()/2.0-(1.0+eigen_ttau.array()/
404  eigen_tau_n.array()).log().sum()/2.0;
405 
406  // compute nlZ_part3=-(nu_n-m.*tau_n)'*((ttau./tau_n.*(nu_n-m.*tau_n)-2*tnu)
407  // ./(ttau+tau_n))/2
408  float64_t nlZ_part3=-(eigen_nu_n-eigen_m.cwiseProduct(eigen_tau_n)).dot(
409  ((eigen_ttau.array()/eigen_tau_n.array()*(eigen_nu_n.array()-
410  eigen_m.array()*eigen_tau_n.array())-2*eigen_tnu.array())/
411  (eigen_ttau.array()+eigen_tau_n.array())).matrix())/2.0;
412 
413  // compute nlZ=nlZ_part1+nlZ_part2+nlZ_part3
414  m_nlZ=nlZ_part1+nlZ_part2+nlZ_part3;
415 }
416 
418 {
419  // create eigen representation of L, sstau, alpha
420  Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols);
421  Map<VectorXd> eigen_sttau(m_sttau.vector, m_sttau.vlen);
422  Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
423 
424  // create shogun and eigen representation of F
426  Map<MatrixXd> eigen_F(m_F.matrix, m_F.num_rows, m_F.num_cols);
427 
428  // solve L*L^T * V = diag(sqrt(ttau))
429  MatrixXd V=eigen_L.triangularView<Upper>().adjoint().solve(
430  MatrixXd(eigen_sttau.asDiagonal()));
431  V=eigen_L.triangularView<Upper>().solve(V);
432 
433  // compute F=alpha*alpha'-repmat(sW,1,n).*solve_chol(L,diag(sW))
434  eigen_F=eigen_alpha*eigen_alpha.adjoint()-eigen_sttau.asDiagonal()*V;
435 }
436 
438  const TParameter* param)
439 {
440  REQUIRE(!strcmp(param->m_name, "scale"), "Can't compute derivative of "
441  "the nagative log marginal likelihood wrt %s.%s parameter\n",
442  get_name(), param->m_name)
443 
444  Map<MatrixXd> eigen_K(m_ktrtr.matrix, m_ktrtr.num_rows, m_ktrtr.num_cols);
445  Map<MatrixXd> eigen_F(m_F.matrix, m_F.num_rows, m_F.num_cols);
446 
447  SGVector<float64_t> result(1);
448 
449  // compute derivative wrt kernel scale: dnlZ=-sum(F.*K*scale*2)/2
450  result[0]=-(eigen_F.cwiseProduct(eigen_K)*m_scale*2.0).sum()/2.0;
451 
452  return result;
453 }
454 
456  const TParameter* param)
457 {
459  return SGVector<float64_t>();
460 }
461 
463  const TParameter* param)
464 {
465  // create eigen representation of the matrix Q
466  Map<MatrixXd> eigen_F(m_F.matrix, m_F.num_rows, m_F.num_cols);
467 
468  REQUIRE(param, "Param not set\n");
469  SGVector<float64_t> result;
470  int64_t len=const_cast<TParameter *>(param)->m_datatype.get_num_elements();
471  result=SGVector<float64_t>(len);
472 
473  for (index_t i=0; i<result.vlen; i++)
474  {
476 
477  if (result.vlen==1)
478  dK=m_kernel->get_parameter_gradient(param);
479  else
480  dK=m_kernel->get_parameter_gradient(param, i);
481 
482  Map<MatrixXd> eigen_dK(dK.matrix, dK.num_rows, dK.num_cols);
483 
484  // compute derivative wrt kernel parameter: dnlZ=-sum(F.*dK*scale^2)/2.0
485  result[i]=-(eigen_F.cwiseProduct(eigen_dK)*CMath::sq(m_scale)).sum()/2.0;
486  }
487 
488  return result;
489 }
490 
492  const TParameter* param)
493 {
495  return SGVector<float64_t>();
496 }
497 
498 #endif /* HAVE_EIGEN3 */

SHOGUN Machine Learning Toolbox - Documentation