Source

Bayesian-Optimization / src / nonparametricprocess.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/*
-------------------------------------------------------------------------
   This file is part of BayesOpt, an efficient C++ library for 
   Bayesian optimization.

   Copyright (C) 2011-2013 Ruben Martinez-Cantin <rmcantin@unizar.es>
 
   BayesOpt is free software: you can redistribute it and/or modify it 
   under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   BayesOpt is distributed in the hope that it will be useful, but 
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
*/


#include <cstdio>
#include "nonparametricprocess.hpp"
#include "log.hpp"
#include "cholesky.hpp"
#include "ublas_extra.hpp"

#include "gaussian_process.hpp"
#include "gaussian_process_ml.hpp"
#include "gaussian_process_normal.hpp"
#include "student_t_process_jef.hpp"
#include "student_t_process_nig.hpp"


namespace bayesopt
{
  
  NonParametricProcess::NonParametricProcess(size_t dim, bopt_params parameters):
    InnerOptimization(), mRegularizer(parameters.noise), 
    mSigma(parameters.sigma_s), dim_(dim)
  { 
    mMinIndex = 0;     mMaxIndex = 0;   
    if (parameters.l_type == L_ML)
      {
	setAlgorithm(BOBYQA);    // local search to avoid underfitting
      }
    else
      {
	setAlgorithm(COMBINED);
      }
    setLimits(1e-10,100.);
    setLearnType(parameters.l_type);
    setKernel(parameters.kernel,dim);
    setMean(parameters.mean,dim);
  }

  NonParametricProcess::~NonParametricProcess(){}


  NonParametricProcess* NonParametricProcess::create(size_t dim, 
						     bopt_params parameters)
  {
    NonParametricProcess* s_ptr;

    std::string name = parameters.surr_name;

    if (!name.compare("GAUSSIAN_PROCESS"))
      s_ptr = new GaussianProcess(dim,parameters);
    else  if(!name.compare("GAUSSIAN_PROCESS_ML"))
      s_ptr = new GaussianProcessML(dim,parameters);
    else  if(!name.compare("GAUSSIAN_PROCESS_NORMAL"))
      s_ptr = new GaussianProcessNormal(dim,parameters);
    else if (!name.compare("STUDENT_T_PROCESS_JEFFREYS"))
      s_ptr = new StudentTProcessNIG(dim,parameters); 
    else if (!name.compare("STUDENT_T_PROCESS_NORMAL_INV_GAMMA"))
      s_ptr = new StudentTProcessNIG(dim,parameters); 
    else
      {
	FILE_LOG(logERROR) << "Error: surrogate function not supported.";
	return NULL;
      }
    return s_ptr;
  };


  int NonParametricProcess::fitInitialSurrogate(bool learnTheta)
  {
    int error = -1;
    if (learnTheta)
      {
	vectord optimalTheta = mKernel->getHyperParameters();
	
	FILE_LOG(logDEBUG) << "Computing kernel parameters. Seed: " 
			   << optimalTheta;
	innerOptimize(optimalTheta);
	mKernel->setHyperParameters(optimalTheta);
	FILE_LOG(logDEBUG) << "Final kernel parameters: " << optimalTheta;	
      }

    error = computeCholeskyCorrelation();

    if (error < 0)
      {
	FILE_LOG(logERROR) << "Error computing the correlation matrix";
	return error;
      }   

    error = precomputePrediction(); 

    if (error < 0)
      {
	FILE_LOG(logERROR) << "Error pre-computing the prediction distribution";
	return error;
      }   

    return 0; 
  } // fitInitialSurrogate


  int NonParametricProcess::updateSurrogateModel( const vectord &Xnew,
						  double Ynew)
  {
    assert( mGPXX[1].size() == Xnew.size() );

    const vectord newK = computeCrossCorrelation(Xnew);
    double selfCorrelation = (*mKernel)(Xnew, Xnew) + mRegularizer;
  
    addSample(Xnew,Ynew);
    addNewPointToCholesky(newK,selfCorrelation);

    int error = precomputePrediction(); 
    if (error < 0)
      {
	FILE_LOG(logERROR) << "Error pre-computing the prediction distribution";
	return error;
      }   

    return 0; 
  } // updateSurrogateModel


  int NonParametricProcess::fullUpdateSurrogateModel( const vectord &Xnew,
						      double Ynew)
  {
    assert( mGPXX[1].size() == Xnew.size() );
    addSample(Xnew,Ynew);
    return fitInitialSurrogate();
  } // fullUpdateSurrogateModel


  //////////////////////////////////////////////////////////////////////////////
  //// Getters and Setters
  void NonParametricProcess::setSamples(const matrixd &x, const vectord &y)
  {
    mGPY = y;
    for (size_t i=0; i<x.size1(); ++i)
      {
	mGPXX.push_back(row(x,i));
	checkBoundsY(i);
      } 
    mMeanV = (*mMean)(mGPXX);
    mFeatM = mMean->getAllFeatures(mGPXX);
  }

  void NonParametricProcess::addSample(const vectord &x, double y)
  {
    using boost::numeric::ublas::column;

    mGPXX.push_back(x);
    mGPY.resize(mGPY.size()+1);  mGPY(mGPY.size()-1) = y;
    checkBoundsY(mGPY.size()-1);

    mMeanV.resize(mMeanV.size()+1);  
    mMeanV(mMeanV.size()-1) = mMean->getMean(x);

    vectord feat = mMean->getFeatures(x);
    mFeatM.resize(feat.size(),mFeatM.size2()+1);  
    column(mFeatM,mFeatM.size2()-1) = feat;

  };

  double NonParametricProcess::getSample(size_t index, vectord &x)
  {
    x = mGPXX[index];
    return mGPY(index);
  }

  double NonParametricProcess::getLastSample(vectord &x)
  {
    size_t last = mGPY.size()-1;
    x = mGPXX[last];
    return mGPY[last];
  }
    
  int NonParametricProcess::setKernel (const vectord &thetav, 
				       const vectord &stheta,
				       std::string k_name, 
				       size_t dim)
  {
    mKernel.reset(mKFactory.create(k_name, dim));
    int error = setKernelPrior(thetav,stheta);
    
    if (mKernel == NULL || error)   return -1;

    mKernel->setHyperParameters(thetav);
    return 0;
  }

  int NonParametricProcess::setKernel (kernel_parameters kernel, 
				       size_t dim)
  {
    size_t n = kernel.n_hp;
    vectord th = utils::array2vector(kernel.hp_mean,n);
    vectord sth = utils::array2vector(kernel.hp_std,n);
    int error = setKernel(th, sth, kernel.name, dim);
    return 0;
  };

  int NonParametricProcess::setKernelPrior (const vectord &theta, 
					    const vectord &s_theta)
  {
    size_t n_theta = theta.size();
    for (size_t i = 0; i<n_theta; ++i)
      {
	boost::math::normal n(theta(i),s_theta(i));
	priorKernel.push_back(n);
      }
    return 0;
  };



  int NonParametricProcess::setMean (const vectord &muv,
				     const vectord &smu,
				     std::string m_name,
				     size_t dim)
  {
    mMean.reset(mPFactory.create(m_name,dim));
    mMu = muv; mS_Mu = smu;

    if (mMean == NULL) 	return -1; 

    //TODO: This might be unnecesary
    mMean->setParameters(muv);
    return 0;
  }

  int NonParametricProcess::setMean (mean_parameters mean, size_t dim)
  {
    size_t n_mu = mean.n_coef;
    vectord vmu = utils::array2vector(mean.coef_mean,n_mu);
    vectord smu = utils::array2vector(mean.coef_std,n_mu);
    return setMean(vmu, smu, mean.name, dim);
  };


  double NonParametricProcess::negativeCrossValidation()
  {
    // This is highly ineffient implementation for comparison purposes.
    size_t n = mGPXX.size();
    size_t last = n-1;
    int error = 0;
    double sum = 0.0;
    vecOfvec tempXX(mGPXX);
    vectord tempY(mGPY);
    vectord tempM(mMeanV);
    matrixd tempF(mFeatM);
    for(size_t i = 0; i<n; ++i)
      {
	vectord x = mGPXX[0];  double y = mGPY(0);
	double m = mMeanV(0);

	mGPXX.erase(mGPXX.begin()); 
	utils::erase(mGPY,mGPY.begin());
	utils::erase(mMeanV,mMeanV.begin());
	utils::erase_column(mFeatM,0);

	fitInitialSurrogate(false);
	ProbabilityDistribution* pd = prediction(x);
	sum += log(pd->pdf(y));
	mGPXX.push_back(x);     
	mGPY.resize(mGPY.size()+1);  mGPY(mGPY.size()-1) = y;
	mMeanV.resize(mGPY.size());  mMeanV(mGPY.size()-1) = m;
	mFeatM.resize(mFeatM.size1(),mFeatM.size2()+1);  
	mFeatM = tempF;
      }
      std::cout << "End" << mGPY.size();
    return -sum;
  }

  double NonParametricProcess::negativeLogPrior()
  {
    double prior = 0.0;
    vectord th = mKernel->getHyperParameters();
    for(size_t i = 0; i<th.size();++i)
      {
	if (priorKernel[i].standard_deviation() > 0)
	  {
	    prior -= log(boost::math::pdf(priorKernel[i],th(i)));
	  }
      }
    return prior;
  }

  double NonParametricProcess::innerEvaluate(const vectord& query)
  { 
    mKernel->setHyperParameters(query);
    double result;
    switch(mLearnType)
      {
      case L_ML:
	result = negativeTotalLogLikelihood(); break;
      case L_MAP:
	result = negativeLogLikelihood()+negativeLogPrior();
	break;
      case L_LOO:
	result = negativeCrossValidation(); break;
      default:
	FILE_LOG(logERROR) << "Learning type not supported";
      }	  
    return result;
  }


  int NonParametricProcess::addNewPointToCholesky(const vectord& correlation,
						  double selfcorrelation)
  {
    vectord newK(correlation);
    utils::append(newK, selfcorrelation);
    utils::cholesky_add_row(mL,newK);
    return 1;
  }


  int NonParametricProcess::computeCholeskyCorrelation()
  {
    size_t nSamples = mGPXX.size();
    mL.resize(nSamples,nSamples);
  
    //  const matrixd K = computeCorrMatrix();
    matrixd K(nSamples,nSamples);
    computeCorrMatrix(K);
    return utils::cholesky_decompose(K,mL);
  }

  int NonParametricProcess::addNewPointToInverse(const vectord& correlation,
						 double selfcorrelation)
  {
    size_t nSamples = correlation.size();
  
    vectord wInvR = prod(correlation,mInvR);
    double wInvRw = inner_prod(wInvR,correlation);
    double Ni = 1/(selfcorrelation - wInvRw);
    vectord Li = -Ni * wInvR;
    mInvR += outer_prod(Li,Li) / Ni;
  
    //TODO: There must be a better way to do this.
    mInvR.resize(nSamples+1,nSamples+1,true);
  
    Li.resize(nSamples+1);
    Li(nSamples) = Ni;
  
    row(mInvR,nSamples) = Li;
    column(mInvR,nSamples) = Li;

    return 1;

  }


  int NonParametricProcess::computeInverseCorrelation()
  {
    const size_t nSamples = mGPXX.size();
    if ( (nSamples != mInvR.size1()) || (nSamples != mInvR.size2()) )
      mInvR.resize(nSamples,nSamples);
    
    const matrixd corrMatrix = computeCorrMatrix();
    return utils::inverse_cholesky(corrMatrix,mInvR);
  }


  int NonParametricProcess::computeCorrMatrix(matrixd& corrMatrix)
  {
    assert(corrMatrix.size1() == mGPXX.size());
    assert(corrMatrix.size2() == mGPXX.size());
    const size_t nSamples = mGPXX.size();
  
    for (size_t ii=0; ii< nSamples; ++ii)
      {
	for (size_t jj=0; jj < ii; ++jj)
	  {
	    corrMatrix(ii,jj) = (*mKernel)(mGPXX[ii], mGPXX[jj]);
	    corrMatrix(jj,ii) = corrMatrix(ii,jj);
	  }
	corrMatrix(ii,ii) = (*mKernel)(mGPXX[ii],mGPXX[ii]) + mRegularizer;
      }
    return 1;
  }



  matrixd NonParametricProcess::computeCorrMatrix()
  {
    const size_t nSamples = mGPXX.size();
    matrixd corrMatrix(nSamples,nSamples);
  
    for (size_t ii=0; ii< nSamples; ++ii)
      {
	for (size_t jj=0; jj < ii; ++jj)
	  {
	    corrMatrix(ii,jj) = (*mKernel)(mGPXX[ii], mGPXX[jj]);
	    corrMatrix(jj,ii) = corrMatrix(ii,jj);
	  }
	corrMatrix(ii,ii) = (*mKernel)(mGPXX[ii],mGPXX[ii]) + mRegularizer;
      }
    return corrMatrix;
  }

  matrixd NonParametricProcess::computeDerivativeCorrMatrix(int dth_index)
  {
    const size_t nSamples = mGPXX.size();
    matrixd corrMatrix(nSamples,nSamples);
  
    for (size_t ii=0; ii< nSamples; ++ii)
      {
	for (size_t jj=0; jj < ii; ++jj)
	  {
	    corrMatrix(ii,jj) = mKernel->gradient(mGPXX[ii],mGPXX[jj], 
						  dth_index);
	    corrMatrix(jj,ii) = corrMatrix(ii,jj);
	  }
	corrMatrix(ii,ii) = mKernel->gradient(mGPXX[ii],mGPXX[ii],dth_index);
      }
    return corrMatrix;
  }



  vectord NonParametricProcess::computeCrossCorrelation(const vectord &query)
  {
    vectord knx(mGPXX.size());

    std::vector<vectord>::const_iterator x_it  = mGPXX.begin();
    std::vector<vectord>::const_iterator x_end = mGPXX.end();
    vectord::iterator k_it = knx.begin();
    while(x_it != x_end)
      {
	*k_it++ = (*mKernel)(*x_it++, query);
      }
    
    return knx;
  }


} //namespace bayesopt
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.