1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Linq;
|
---|
25 | using HeuristicLab.Common;
|
---|
26 | using HeuristicLab.Core;
|
---|
27 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
28 | using HeuristicLab.Problems.DataAnalysis;
|
---|
29 |
|
---|
30 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
31 | /// <summary>
|
---|
32 | /// Represents a Gaussian process model.
|
---|
33 | /// </summary>
|
---|
34 | [StorableClass]
|
---|
35 | [Item("GaussianProcessModel", "Represents a Gaussian process posterior.")]
|
---|
36 | public sealed class GaussianProcessModel : NamedItem, IGaussianProcessModel {
|
---|
37 | [Storable]
|
---|
38 | private double negativeLogLikelihood;
|
---|
39 | public double NegativeLogLikelihood {
|
---|
40 | get { return negativeLogLikelihood; }
|
---|
41 | }
|
---|
42 |
|
---|
43 | [Storable]
|
---|
44 | private ICovarianceFunction covarianceFunction;
|
---|
45 | public ICovarianceFunction CovarianceFunction {
|
---|
46 | get { return covarianceFunction; }
|
---|
47 | }
|
---|
48 | [Storable]
|
---|
49 | private IMeanFunction meanFunction;
|
---|
50 | public IMeanFunction MeanFunction {
|
---|
51 | get { return meanFunction; }
|
---|
52 | }
|
---|
53 | [Storable]
|
---|
54 | private string targetVariable;
|
---|
55 | public string TargetVariable {
|
---|
56 | get { return targetVariable; }
|
---|
57 | }
|
---|
58 | [Storable]
|
---|
59 | private string[] allowedInputVariables;
|
---|
60 | public string[] AllowedInputVariables {
|
---|
61 | get { return allowedInputVariables; }
|
---|
62 | }
|
---|
63 |
|
---|
64 | [Storable]
|
---|
65 | private double[] alpha;
|
---|
66 | [Storable]
|
---|
67 | private double sqrSigmaNoise;
|
---|
68 |
|
---|
69 | [Storable]
|
---|
70 | private double[,] l;
|
---|
71 |
|
---|
72 | [Storable]
|
---|
73 | private double[,] x;
|
---|
74 | [Storable]
|
---|
75 | private Scaling inputScaling;
|
---|
76 | [Storable]
|
---|
77 | private Scaling targetScaling;
|
---|
78 |
|
---|
79 |
|
---|
80 | [StorableConstructor]
|
---|
81 | private GaussianProcessModel(bool deserializing) : base(deserializing) { }
|
---|
82 | private GaussianProcessModel(GaussianProcessModel original, Cloner cloner)
|
---|
83 | : base(original, cloner) {
|
---|
84 | this.meanFunction = cloner.Clone(original.meanFunction);
|
---|
85 | this.covarianceFunction = cloner.Clone(original.covarianceFunction);
|
---|
86 | this.inputScaling = cloner.Clone(original.inputScaling);
|
---|
87 | this.targetScaling = cloner.Clone(original.targetScaling);
|
---|
88 | this.negativeLogLikelihood = original.negativeLogLikelihood;
|
---|
89 | this.targetVariable = original.targetVariable;
|
---|
90 | this.sqrSigmaNoise = original.sqrSigmaNoise;
|
---|
91 |
|
---|
92 | // shallow copies of arrays because they cannot be modified
|
---|
93 | this.allowedInputVariables = original.allowedInputVariables;
|
---|
94 | this.alpha = original.alpha;
|
---|
95 | this.l = original.l;
|
---|
96 | this.x = original.x;
|
---|
97 | }
|
---|
98 | public GaussianProcessModel(Dataset ds, string targetVariable, IEnumerable<string> allowedInputVariables, IEnumerable<int> rows,
|
---|
99 | IEnumerable<double> hyp, IMeanFunction meanFunction, ICovarianceFunction covarianceFunction)
|
---|
100 | : base() {
|
---|
101 | this.name = ItemName;
|
---|
102 | this.description = ItemDescription;
|
---|
103 | this.meanFunction = (IMeanFunction)meanFunction.Clone();
|
---|
104 | this.covarianceFunction = (ICovarianceFunction)covarianceFunction.Clone();
|
---|
105 | this.targetVariable = targetVariable;
|
---|
106 | this.allowedInputVariables = allowedInputVariables.ToArray();
|
---|
107 |
|
---|
108 | sqrSigmaNoise = Math.Exp(2.0 * hyp.First());
|
---|
109 | sqrSigmaNoise = Math.Max(10E-6, sqrSigmaNoise); // lower limit for the noise level
|
---|
110 |
|
---|
111 | int nVariables = this.allowedInputVariables.Length;
|
---|
112 | this.meanFunction.SetParameter(hyp.Skip(1)
|
---|
113 | .Take(this.meanFunction.GetNumberOfParameters(nVariables))
|
---|
114 | .ToArray());
|
---|
115 | this.covarianceFunction.SetParameter(hyp.Skip(1 + this.meanFunction.GetNumberOfParameters(nVariables))
|
---|
116 | .Take(this.covarianceFunction.GetNumberOfParameters(nVariables))
|
---|
117 | .ToArray());
|
---|
118 |
|
---|
119 | CalculateModel(ds, rows);
|
---|
120 | }
|
---|
121 |
|
---|
122 | private void CalculateModel(Dataset ds, IEnumerable<int> rows) {
|
---|
123 | inputScaling = new Scaling(ds, allowedInputVariables, rows);
|
---|
124 | x = AlglibUtil.PrepareAndScaleInputMatrix(ds, allowedInputVariables, rows, inputScaling);
|
---|
125 |
|
---|
126 |
|
---|
127 | targetScaling = new Scaling(ds, new string[] { targetVariable }, rows);
|
---|
128 | var y = targetScaling.GetScaledValues(ds, targetVariable, rows);
|
---|
129 |
|
---|
130 | int n = x.GetLength(0);
|
---|
131 | l = new double[n, n];
|
---|
132 |
|
---|
133 | meanFunction.SetData(x);
|
---|
134 | covarianceFunction.SetData(x);
|
---|
135 |
|
---|
136 | // calculate means and covariances
|
---|
137 | double[] m = meanFunction.GetMean(x);
|
---|
138 | for (int i = 0; i < n; i++) {
|
---|
139 |
|
---|
140 | for (int j = i; j < n; j++) {
|
---|
141 | l[j, i] = covarianceFunction.GetCovariance(i, j) / sqrSigmaNoise;
|
---|
142 | if (j == i) l[j, i] += 1.0;
|
---|
143 | }
|
---|
144 | }
|
---|
145 |
|
---|
146 | // cholesky decomposition
|
---|
147 | int info;
|
---|
148 | alglib.densesolverreport denseSolveRep;
|
---|
149 |
|
---|
150 | var res = alglib.trfac.spdmatrixcholesky(ref l, n, false);
|
---|
151 | if (!res) throw new InvalidOperationException("Matrix is not positive semidefinite");
|
---|
152 |
|
---|
153 | // calculate sum of diagonal elements for likelihood
|
---|
154 | double diagSum = Enumerable.Range(0, n).Select(i => Math.Log(l[i, i])).Sum();
|
---|
155 |
|
---|
156 | // solve for alpha
|
---|
157 | double[] ym = y.Zip(m, (a, b) => a - b).ToArray();
|
---|
158 |
|
---|
159 | alglib.spdmatrixcholeskysolve(l, n, false, ym, out info, out denseSolveRep, out alpha);
|
---|
160 | for (int i = 0; i < alpha.Length; i++)
|
---|
161 | alpha[i] = alpha[i] / sqrSigmaNoise;
|
---|
162 | negativeLogLikelihood = 0.5 * Util.ScalarProd(ym, alpha) + diagSum + (n / 2.0) * Math.Log(2.0 * Math.PI * sqrSigmaNoise);
|
---|
163 | }
|
---|
164 |
|
---|
165 | public double[] GetHyperparameterGradients() {
|
---|
166 | // derivatives
|
---|
167 | int n = x.GetLength(0);
|
---|
168 | int nAllowedVariables = x.GetLength(1);
|
---|
169 |
|
---|
170 | int info;
|
---|
171 | alglib.matinvreport matInvRep;
|
---|
172 |
|
---|
173 | alglib.spdmatrixcholeskyinverse(ref l, n, false, out info, out matInvRep);
|
---|
174 | if (info != 1) throw new ArgumentException("Can't invert matrix to calculate gradients.");
|
---|
175 | for (int i = 0; i < n; i++) {
|
---|
176 | for (int j = 0; j <= i; j++)
|
---|
177 | l[i, j] = l[i, j] / sqrSigmaNoise - alpha[i] * alpha[j];
|
---|
178 | }
|
---|
179 |
|
---|
180 | double noiseGradient = sqrSigmaNoise * Enumerable.Range(0, n).Select(i => l[i, i]).Sum();
|
---|
181 |
|
---|
182 | double[] meanGradients = new double[meanFunction.GetNumberOfParameters(nAllowedVariables)];
|
---|
183 | for (int i = 0; i < meanGradients.Length; i++) {
|
---|
184 | var meanGrad = meanFunction.GetGradients(i, x);
|
---|
185 | meanGradients[i] = -Util.ScalarProd(meanGrad, alpha);
|
---|
186 | }
|
---|
187 |
|
---|
188 | double[] covGradients = new double[covarianceFunction.GetNumberOfParameters(nAllowedVariables)];
|
---|
189 | if (covGradients.Length > 0) {
|
---|
190 | for (int i = 0; i < n; i++) {
|
---|
191 | for (int k = 0; k < covGradients.Length; k++) {
|
---|
192 | for (int j = 0; j < i; j++) {
|
---|
193 | covGradients[k] += l[i, j] * covarianceFunction.GetGradient(i, j, k);
|
---|
194 | }
|
---|
195 | covGradients[k] += 0.5 * l[i, i] * covarianceFunction.GetGradient(i, i, k);
|
---|
196 | }
|
---|
197 | }
|
---|
198 | }
|
---|
199 |
|
---|
200 | return new double[] { noiseGradient }
|
---|
201 | .Concat(meanGradients)
|
---|
202 | .Concat(covGradients).ToArray();
|
---|
203 | }
|
---|
204 |
|
---|
205 |
|
---|
206 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
207 | return new GaussianProcessModel(this, cloner);
|
---|
208 | }
|
---|
209 |
|
---|
210 | #region IRegressionModel Members
|
---|
211 | public IEnumerable<double> GetEstimatedValues(Dataset dataset, IEnumerable<int> rows) {
|
---|
212 | return GetEstimatedValuesHelper(dataset, rows);
|
---|
213 | }
|
---|
214 | public GaussianProcessRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
|
---|
215 | return new GaussianProcessRegressionSolution(this, problemData);
|
---|
216 | }
|
---|
217 | IRegressionSolution IRegressionModel.CreateRegressionSolution(IRegressionProblemData problemData) {
|
---|
218 | return CreateRegressionSolution(problemData);
|
---|
219 | }
|
---|
220 | #endregion
|
---|
221 |
|
---|
222 | private IEnumerable<double> GetEstimatedValuesHelper(Dataset dataset, IEnumerable<int> rows) {
|
---|
223 | var newX = AlglibUtil.PrepareAndScaleInputMatrix(dataset, allowedInputVariables, rows, inputScaling);
|
---|
224 | int newN = newX.GetLength(0);
|
---|
225 | int n = x.GetLength(0);
|
---|
226 | // var predMean = new double[newN];
|
---|
227 | // predVar = new double[newN];
|
---|
228 |
|
---|
229 |
|
---|
230 |
|
---|
231 | // var kss = new double[newN];
|
---|
232 | var Ks = new double[newN, n];
|
---|
233 | double[,] sWKs = new double[n, newN];
|
---|
234 | // double[,] v;
|
---|
235 |
|
---|
236 |
|
---|
237 | // for stddev
|
---|
238 | //covarianceFunction.SetParameter(covHyp, newX);
|
---|
239 | //kss = covarianceFunction.GetDiagonalCovariances();
|
---|
240 |
|
---|
241 | covarianceFunction.SetData(x, newX);
|
---|
242 | meanFunction.SetData(newX);
|
---|
243 | var ms = meanFunction.GetMean(newX);
|
---|
244 | for (int i = 0; i < newN; i++) {
|
---|
245 |
|
---|
246 | for (int j = 0; j < n; j++) {
|
---|
247 | Ks[i, j] = covarianceFunction.GetCovariance(j, i);
|
---|
248 | sWKs[j, i] = Ks[i, j] / Math.Sqrt(sqrSigmaNoise);
|
---|
249 | }
|
---|
250 | }
|
---|
251 |
|
---|
252 | // for stddev
|
---|
253 | // alglib.rmatrixsolvem(l, n, sWKs, newN, true, out info, out denseSolveRep, out v);
|
---|
254 |
|
---|
255 | double targetScaleMin, targetScaleMax;
|
---|
256 | targetScaling.GetScalingParameters(targetVariable, out targetScaleMin, out targetScaleMax);
|
---|
257 | return Enumerable.Range(0, newN)
|
---|
258 | .Select(i => ms[i] + Util.ScalarProd(Util.GetRow(Ks, i), alpha))
|
---|
259 | .Select(m => m * (targetScaleMax - targetScaleMin) + targetScaleMin);
|
---|
260 | //for (int i = 0; i < newN; i++) {
|
---|
261 | // // predMean[i] = ms[i] + prod(GetRow(Ks, i), alpha);
|
---|
262 | // // var sumV2 = prod(GetCol(v, i), GetCol(v, i));
|
---|
263 | // // predVar[i] = kss[i] - sumV2;
|
---|
264 | //}
|
---|
265 |
|
---|
266 | }
|
---|
267 | }
|
---|
268 | }
|
---|