-
Notifications
You must be signed in to change notification settings - Fork 71
/
GaussianProcess.cpp
80 lines (68 loc) · 1.88 KB
/
GaussianProcess.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
#include <vnl/algo/vnl_cholesky.h>
class MultiGaussian {
public:
Vector mean;
Matrix covariance;
MultiGaussian(Vector const& mean, Matrix const& covariance):
mean(mean), covariance(covariance) {}
};
template <class T>
class GaussianProcess {
public:
typedef double (*CovarianceFunction)(const T&, const T&);
private:
vector<T> inputs;
CovarianceFunction covariancefunction;
private:
Matrix L;
Vector alpha;
Matrix getcovariancematrix(vector<T> const& in1,
vector<T> const& in2) const
{
Matrix K(in1.size(), in2.size());
for(int i=0; i<in1.size(); i++)
for(int j=0; j<in2.size(); j++)
K(i,j) = covariancefunction(in1[i], in2[j]);
return K;
}
public:
GaussianProcess(vector<T> const& inputs,
Vector const& targets,
CovarianceFunction covariancefunction,
double noise=0.0):
inputs(inputs), covariancefunction(covariancefunction)
{
Matrix K = getcovariancematrix(inputs, inputs);
for(int i=0; i<inputs.size(); i++)
K[i][i] += noise;
// todo: do we need the "verbose" mode in cholesky?
vnl_cholesky chol(K);
L = chol.lower_triangle();
alpha = chol.solve(targets);
}
Vector getmeans(vector<T> const &tests) const {
Matrix KK = getcovariancematrix(inputs, tests);
return KK.transpose() * alpha;
}
double getmean(T const& test) const {
return getmeans(vector<T>(1, test))[0];
}
};
template <class T>
class MeanAdjustedGaussianProcess {
double mean;
const GaussianProcess<T> gp;
public:
MeanAdjustedGaussianProcess(vector<T> const& inputs,
Vector const& targets,
typename GaussianProcess<T>::CovarianceFunction
covariancefunction,
double noise=0.0):
mean(targets.mean()),
gp(GaussianProcess<T>(inputs, targets - mean,
covariancefunction, noise))
{}
double getmean(T const& test) const {
return gp.getmean(test) + mean;
}
};