1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2016 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;
|
---|
28 | using HeuristicLab.Problems.DataAnalysis;
|
---|
29 |
|
---|
30 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
31 | /// <summary>
|
---|
32 | /// Represents a Gaussian process model.
|
---|
33 | /// </summary>
|
---|
34 | [StorableType("36ca62fa-4766-4269-b5f1-3bc24c0ed2e1")]
|
---|
35 | [Item("GaussianProcessModel", "Represents a Gaussian process posterior.")]
|
---|
36 | public sealed class GaussianProcessModel : RegressionModel, IGaussianProcessModel {
|
---|
37 | public override IEnumerable<string> VariablesUsedForPrediction {
|
---|
38 | get { return allowedInputVariables; }
|
---|
39 | }
|
---|
40 |
|
---|
41 | [Storable]
|
---|
42 | private double negativeLogLikelihood;
|
---|
43 | public double NegativeLogLikelihood {
|
---|
44 | get { return negativeLogLikelihood; }
|
---|
45 | }
|
---|
46 |
|
---|
47 | [Storable]
|
---|
48 | private double negativeLooPredictiveProbability;
|
---|
49 | public double NegativeLooPredictiveProbability {
|
---|
50 | get { return negativeLooPredictiveProbability; }
|
---|
51 | }
|
---|
52 |
|
---|
53 | [Storable]
|
---|
54 | private double[] hyperparameterGradients;
|
---|
55 | public double[] HyperparameterGradients {
|
---|
56 | get {
|
---|
57 | var copy = new double[hyperparameterGradients.Length];
|
---|
58 | Array.Copy(hyperparameterGradients, copy, copy.Length);
|
---|
59 | return copy;
|
---|
60 | }
|
---|
61 | }
|
---|
62 |
|
---|
63 | [Storable]
|
---|
64 | private ICovarianceFunction covarianceFunction;
|
---|
65 | public ICovarianceFunction CovarianceFunction {
|
---|
66 | get { return covarianceFunction; }
|
---|
67 | }
|
---|
68 | [Storable]
|
---|
69 | private IMeanFunction meanFunction;
|
---|
70 | public IMeanFunction MeanFunction {
|
---|
71 | get { return meanFunction; }
|
---|
72 | }
|
---|
73 |
|
---|
74 | [Storable]
|
---|
75 | private string[] allowedInputVariables;
|
---|
76 | public string[] AllowedInputVariables {
|
---|
77 | get { return allowedInputVariables; }
|
---|
78 | }
|
---|
79 |
|
---|
80 | [Storable]
|
---|
81 | private double[] alpha;
|
---|
82 | [Storable]
|
---|
83 | private double sqrSigmaNoise;
|
---|
84 | public double SigmaNoise {
|
---|
85 | get { return Math.Sqrt(sqrSigmaNoise); }
|
---|
86 | }
|
---|
87 |
|
---|
88 | [Storable]
|
---|
89 | private double[] meanParameter;
|
---|
90 | [Storable]
|
---|
91 | private double[] covarianceParameter;
|
---|
92 |
|
---|
93 | private double[,] l; // used to be storable in previous versions (is calculated lazily now)
|
---|
94 | private double[,] x; // scaled training dataset, used to be storable in previous versions (is calculated lazily now)
|
---|
95 |
|
---|
96 | // BackwardsCompatibility3.4
|
---|
97 | #region Backwards compatible code, remove with 3.5
|
---|
98 | [Storable(Name = "l")] // restore if available but don't store anymore
|
---|
99 | private double[,] l_storable {
|
---|
100 | set { this.l = value; }
|
---|
101 | get {
|
---|
102 | if (trainingDataset == null) return l; // this model has been created with an old version
|
---|
103 | else return null; // if the training dataset is available l should not be serialized
|
---|
104 | }
|
---|
105 | }
|
---|
106 | [Storable(Name = "x")] // restore if available but don't store anymore
|
---|
107 | private double[,] x_storable {
|
---|
108 | set { this.x = value; }
|
---|
109 | get {
|
---|
110 | if (trainingDataset == null) return x; // this model has been created with an old version
|
---|
111 | else return null; // if the training dataset is available x should not be serialized
|
---|
112 | }
|
---|
113 | }
|
---|
114 | #endregion
|
---|
115 |
|
---|
116 |
|
---|
117 | [Storable]
|
---|
118 | private IDataset trainingDataset; // it is better to store the original training dataset completely because this is more efficient in persistence
|
---|
119 | [Storable]
|
---|
120 | private int[] trainingRows;
|
---|
121 |
|
---|
122 | [Storable]
|
---|
123 | private Scaling inputScaling;
|
---|
124 |
|
---|
125 |
|
---|
126 | [StorableConstructor]
|
---|
127 | private GaussianProcessModel(bool deserializing) : base(deserializing) { }
|
---|
128 | private GaussianProcessModel(GaussianProcessModel original, Cloner cloner)
|
---|
129 | : base(original, cloner) {
|
---|
130 | this.meanFunction = cloner.Clone(original.meanFunction);
|
---|
131 | this.covarianceFunction = cloner.Clone(original.covarianceFunction);
|
---|
132 | if (original.inputScaling != null)
|
---|
133 | this.inputScaling = cloner.Clone(original.inputScaling);
|
---|
134 | this.trainingDataset = cloner.Clone(original.trainingDataset);
|
---|
135 | this.negativeLogLikelihood = original.negativeLogLikelihood;
|
---|
136 | this.negativeLooPredictiveProbability = original.negativeLooPredictiveProbability;
|
---|
137 | this.sqrSigmaNoise = original.sqrSigmaNoise;
|
---|
138 | if (original.meanParameter != null) {
|
---|
139 | this.meanParameter = (double[])original.meanParameter.Clone();
|
---|
140 | }
|
---|
141 | if (original.covarianceParameter != null) {
|
---|
142 | this.covarianceParameter = (double[])original.covarianceParameter.Clone();
|
---|
143 | }
|
---|
144 |
|
---|
145 | // shallow copies of arrays because they cannot be modified
|
---|
146 | this.trainingRows = original.trainingRows;
|
---|
147 | this.allowedInputVariables = original.allowedInputVariables;
|
---|
148 | this.alpha = original.alpha;
|
---|
149 | this.l = original.l;
|
---|
150 | this.x = original.x;
|
---|
151 | }
|
---|
152 | public GaussianProcessModel(IDataset ds, string targetVariable, IEnumerable<string> allowedInputVariables, IEnumerable<int> rows,
|
---|
153 | IEnumerable<double> hyp, IMeanFunction meanFunction, ICovarianceFunction covarianceFunction,
|
---|
154 | bool scaleInputs = true)
|
---|
155 | : base(targetVariable) {
|
---|
156 | this.name = ItemName;
|
---|
157 | this.description = ItemDescription;
|
---|
158 | this.meanFunction = (IMeanFunction)meanFunction.Clone();
|
---|
159 | this.covarianceFunction = (ICovarianceFunction)covarianceFunction.Clone();
|
---|
160 | this.allowedInputVariables = allowedInputVariables.ToArray();
|
---|
161 |
|
---|
162 |
|
---|
163 | int nVariables = this.allowedInputVariables.Length;
|
---|
164 | meanParameter = hyp
|
---|
165 | .Take(this.meanFunction.GetNumberOfParameters(nVariables))
|
---|
166 | .ToArray();
|
---|
167 |
|
---|
168 | covarianceParameter = hyp.Skip(this.meanFunction.GetNumberOfParameters(nVariables))
|
---|
169 | .Take(this.covarianceFunction.GetNumberOfParameters(nVariables))
|
---|
170 | .ToArray();
|
---|
171 | sqrSigmaNoise = Math.Exp(2.0 * hyp.Last());
|
---|
172 | try {
|
---|
173 | CalculateModel(ds, rows, scaleInputs);
|
---|
174 | } catch (alglib.alglibexception ae) {
|
---|
175 | // wrap exception so that calling code doesn't have to know about alglib implementation
|
---|
176 | throw new ArgumentException("There was a problem in the calculation of the Gaussian process model", ae);
|
---|
177 | }
|
---|
178 | }
|
---|
179 |
|
---|
180 | private void CalculateModel(IDataset ds, IEnumerable<int> rows, bool scaleInputs = true) {
|
---|
181 | this.trainingDataset = (IDataset)ds.Clone();
|
---|
182 | this.trainingRows = rows.ToArray();
|
---|
183 | this.inputScaling = scaleInputs ? new Scaling(ds, allowedInputVariables, rows) : null;
|
---|
184 |
|
---|
185 | x = GetData(ds, this.allowedInputVariables, this.trainingRows, this.inputScaling);
|
---|
186 |
|
---|
187 | IEnumerable<double> y;
|
---|
188 | y = ds.GetDoubleValues(TargetVariable, rows);
|
---|
189 |
|
---|
190 | int n = x.GetLength(0);
|
---|
191 |
|
---|
192 | var columns = Enumerable.Range(0, x.GetLength(1)).ToArray();
|
---|
193 | // calculate cholesky decomposed (lower triangular) covariance matrix
|
---|
194 | var cov = covarianceFunction.GetParameterizedCovarianceFunction(covarianceParameter, columns);
|
---|
195 | this.l = CalculateL(x, cov, sqrSigmaNoise);
|
---|
196 |
|
---|
197 | // calculate mean
|
---|
198 | var mean = meanFunction.GetParameterizedMeanFunction(meanParameter, columns);
|
---|
199 | double[] m = Enumerable.Range(0, x.GetLength(0))
|
---|
200 | .Select(r => mean.Mean(x, r))
|
---|
201 | .ToArray();
|
---|
202 |
|
---|
203 | // calculate sum of diagonal elements for likelihood
|
---|
204 | double diagSum = Enumerable.Range(0, n).Select(i => Math.Log(l[i, i])).Sum();
|
---|
205 |
|
---|
206 | // solve for alpha
|
---|
207 | double[] ym = y.Zip(m, (a, b) => a - b).ToArray();
|
---|
208 |
|
---|
209 | int info;
|
---|
210 | alglib.densesolverreport denseSolveRep;
|
---|
211 |
|
---|
212 | alglib.spdmatrixcholeskysolve(l, n, false, ym, out info, out denseSolveRep, out alpha);
|
---|
213 | for (int i = 0; i < alpha.Length; i++)
|
---|
214 | alpha[i] = alpha[i] / sqrSigmaNoise;
|
---|
215 | negativeLogLikelihood = 0.5 * Util.ScalarProd(ym, alpha) + diagSum + (n / 2.0) * Math.Log(2.0 * Math.PI * sqrSigmaNoise);
|
---|
216 |
|
---|
217 | // derivatives
|
---|
218 | int nAllowedVariables = x.GetLength(1);
|
---|
219 |
|
---|
220 | alglib.matinvreport matInvRep;
|
---|
221 | double[,] lCopy = new double[l.GetLength(0), l.GetLength(1)];
|
---|
222 | Array.Copy(l, lCopy, lCopy.Length);
|
---|
223 |
|
---|
224 | alglib.spdmatrixcholeskyinverse(ref lCopy, n, false, out info, out matInvRep);
|
---|
225 | if (info != 1) throw new ArgumentException("Can't invert matrix to calculate gradients.");
|
---|
226 |
|
---|
227 | // LOOCV log predictive probability (GPML page 116 and 117)
|
---|
228 | var sumLoo = 0.0;
|
---|
229 | var ki = new double[n];
|
---|
230 | for (int i = 0; i < n; i++) {
|
---|
231 | for (int j = 0; j < n; j++) ki[j] = cov.Covariance(x, i, j);
|
---|
232 | var yi = Util.ScalarProd(ki, alpha);
|
---|
233 | var yi_loo = yi - alpha[i] / lCopy[i, i] / sqrSigmaNoise;
|
---|
234 | var s2_loo = sqrSigmaNoise / lCopy[i, i];
|
---|
235 | var err = ym[i] - yi_loo;
|
---|
236 | var nll_loo = Math.Log(s2_loo) + err * err / s2_loo;
|
---|
237 | sumLoo += nll_loo;
|
---|
238 | }
|
---|
239 | sumLoo += n * Math.Log(2 * Math.PI);
|
---|
240 | negativeLooPredictiveProbability = 0.5 * sumLoo;
|
---|
241 |
|
---|
242 | for (int i = 0; i < n; i++) {
|
---|
243 | for (int j = 0; j <= i; j++)
|
---|
244 | lCopy[i, j] = lCopy[i, j] / sqrSigmaNoise - alpha[i] * alpha[j];
|
---|
245 | }
|
---|
246 |
|
---|
247 | double noiseGradient = sqrSigmaNoise * Enumerable.Range(0, n).Select(i => lCopy[i, i]).Sum();
|
---|
248 |
|
---|
249 | double[] meanGradients = new double[meanFunction.GetNumberOfParameters(nAllowedVariables)];
|
---|
250 | for (int k = 0; k < meanGradients.Length; k++) {
|
---|
251 | var meanGrad = new double[alpha.Length];
|
---|
252 | for (int g = 0; g < meanGrad.Length; g++)
|
---|
253 | meanGrad[g] = mean.Gradient(x, g, k);
|
---|
254 | meanGradients[k] = -Util.ScalarProd(meanGrad, alpha);
|
---|
255 | }
|
---|
256 |
|
---|
257 | double[] covGradients = new double[covarianceFunction.GetNumberOfParameters(nAllowedVariables)];
|
---|
258 | if (covGradients.Length > 0) {
|
---|
259 | for (int i = 0; i < n; i++) {
|
---|
260 | for (int j = 0; j < i; j++) {
|
---|
261 | var g = cov.CovarianceGradient(x, i, j);
|
---|
262 | for (int k = 0; k < covGradients.Length; k++) {
|
---|
263 | covGradients[k] += lCopy[i, j] * g[k];
|
---|
264 | }
|
---|
265 | }
|
---|
266 |
|
---|
267 | var gDiag = cov.CovarianceGradient(x, i, i);
|
---|
268 | for (int k = 0; k < covGradients.Length; k++) {
|
---|
269 | // diag
|
---|
270 | covGradients[k] += 0.5 * lCopy[i, i] * gDiag[k];
|
---|
271 | }
|
---|
272 | }
|
---|
273 | }
|
---|
274 |
|
---|
275 | hyperparameterGradients =
|
---|
276 | meanGradients
|
---|
277 | .Concat(covGradients)
|
---|
278 | .Concat(new double[] { noiseGradient }).ToArray();
|
---|
279 |
|
---|
280 | }
|
---|
281 |
|
---|
282 | private static double[,] GetData(IDataset ds, IEnumerable<string> allowedInputs, IEnumerable<int> rows, Scaling scaling) {
|
---|
283 | if (scaling != null) {
|
---|
284 | // BackwardsCompatibility3.3
|
---|
285 | #region Backwards compatible code, remove with 3.4
|
---|
286 | // TODO: completely remove Scaling class
|
---|
287 | List<string> variablesList = allowedInputs.ToList();
|
---|
288 | List<int> rowsList = rows.ToList();
|
---|
289 |
|
---|
290 | double[,] matrix = new double[rowsList.Count, variablesList.Count];
|
---|
291 |
|
---|
292 | int col = 0;
|
---|
293 | foreach (string column in variablesList) {
|
---|
294 | var values = scaling.GetScaledValues(ds, column, rowsList);
|
---|
295 | int row = 0;
|
---|
296 | foreach (var value in values) {
|
---|
297 | matrix[row, col] = value;
|
---|
298 | row++;
|
---|
299 | }
|
---|
300 | col++;
|
---|
301 | }
|
---|
302 | return matrix;
|
---|
303 | #endregion
|
---|
304 | } else {
|
---|
305 | return ds.ToArray(allowedInputs, rows);
|
---|
306 | }
|
---|
307 | }
|
---|
308 |
|
---|
309 | private static double[,] CalculateL(double[,] x, ParameterizedCovarianceFunction cov, double sqrSigmaNoise) {
|
---|
310 | int n = x.GetLength(0);
|
---|
311 | var l = new double[n, n];
|
---|
312 |
|
---|
313 | // calculate covariances
|
---|
314 | for (int i = 0; i < n; i++) {
|
---|
315 | for (int j = i; j < n; j++) {
|
---|
316 | l[j, i] = cov.Covariance(x, i, j) / sqrSigmaNoise;
|
---|
317 | if (j == i) l[j, i] += 1.0;
|
---|
318 | }
|
---|
319 | }
|
---|
320 |
|
---|
321 | // cholesky decomposition
|
---|
322 | var res = alglib.trfac.spdmatrixcholesky(ref l, n, false);
|
---|
323 | if (!res) throw new ArgumentException("Matrix is not positive semidefinite");
|
---|
324 | return l;
|
---|
325 | }
|
---|
326 |
|
---|
327 |
|
---|
328 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
329 | return new GaussianProcessModel(this, cloner);
|
---|
330 | }
|
---|
331 |
|
---|
332 | // is called by the solution creator to set all parameter values of the covariance and mean function
|
---|
333 | // to the optimized values (necessary to make the values visible in the GUI)
|
---|
334 | public void FixParameters() {
|
---|
335 | covarianceFunction.SetParameter(covarianceParameter);
|
---|
336 | meanFunction.SetParameter(meanParameter);
|
---|
337 | covarianceParameter = new double[0];
|
---|
338 | meanParameter = new double[0];
|
---|
339 | }
|
---|
340 |
|
---|
341 | #region IRegressionModel Members
|
---|
342 | public override IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
|
---|
343 | return GetEstimatedValuesHelper(dataset, rows);
|
---|
344 | }
|
---|
345 | public override IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
|
---|
346 | return new GaussianProcessRegressionSolution(this, new RegressionProblemData(problemData));
|
---|
347 | }
|
---|
348 | #endregion
|
---|
349 |
|
---|
350 |
|
---|
351 | private IEnumerable<double> GetEstimatedValuesHelper(IDataset dataset, IEnumerable<int> rows) {
|
---|
352 | try {
|
---|
353 | if (x == null) {
|
---|
354 | x = GetData(trainingDataset, allowedInputVariables, trainingRows, inputScaling);
|
---|
355 | }
|
---|
356 | int n = x.GetLength(0);
|
---|
357 |
|
---|
358 | double[,] newX = GetData(dataset, allowedInputVariables, rows, inputScaling);
|
---|
359 | int newN = newX.GetLength(0);
|
---|
360 |
|
---|
361 | var Ks = new double[newN][];
|
---|
362 | var columns = Enumerable.Range(0, newX.GetLength(1)).ToArray();
|
---|
363 | var mean = meanFunction.GetParameterizedMeanFunction(meanParameter, columns);
|
---|
364 | var ms = Enumerable.Range(0, newX.GetLength(0))
|
---|
365 | .Select(r => mean.Mean(newX, r))
|
---|
366 | .ToArray();
|
---|
367 | var cov = covarianceFunction.GetParameterizedCovarianceFunction(covarianceParameter, columns);
|
---|
368 | for (int i = 0; i < newN; i++) {
|
---|
369 | Ks[i] = new double[n];
|
---|
370 | for (int j = 0; j < n; j++) {
|
---|
371 | Ks[i][j] = cov.CrossCovariance(x, newX, j, i);
|
---|
372 | }
|
---|
373 | }
|
---|
374 |
|
---|
375 | return Enumerable.Range(0, newN)
|
---|
376 | .Select(i => ms[i] + Util.ScalarProd(Ks[i], alpha));
|
---|
377 | } catch (alglib.alglibexception ae) {
|
---|
378 | // wrap exception so that calling code doesn't have to know about alglib implementation
|
---|
379 | throw new ArgumentException("There was a problem in the calculation of the Gaussian process model", ae);
|
---|
380 | }
|
---|
381 | }
|
---|
382 |
|
---|
383 | public IEnumerable<double> GetEstimatedVariances(IDataset dataset, IEnumerable<int> rows) {
|
---|
384 | try {
|
---|
385 | if (x == null) {
|
---|
386 | x = GetData(trainingDataset, allowedInputVariables, trainingRows, inputScaling);
|
---|
387 | }
|
---|
388 | int n = x.GetLength(0);
|
---|
389 |
|
---|
390 | var newX = GetData(dataset, allowedInputVariables, rows, inputScaling);
|
---|
391 | int newN = newX.GetLength(0);
|
---|
392 |
|
---|
393 | var kss = new double[newN];
|
---|
394 | double[,] sWKs = new double[n, newN];
|
---|
395 | var columns = Enumerable.Range(0, newX.GetLength(1)).ToArray();
|
---|
396 | var cov = covarianceFunction.GetParameterizedCovarianceFunction(covarianceParameter, columns);
|
---|
397 |
|
---|
398 | if (l == null) {
|
---|
399 | l = CalculateL(x, cov, sqrSigmaNoise);
|
---|
400 | }
|
---|
401 |
|
---|
402 | // for stddev
|
---|
403 | for (int i = 0; i < newN; i++)
|
---|
404 | kss[i] = cov.Covariance(newX, i, i);
|
---|
405 |
|
---|
406 | for (int i = 0; i < newN; i++) {
|
---|
407 | for (int j = 0; j < n; j++) {
|
---|
408 | sWKs[j, i] = cov.CrossCovariance(x, newX, j, i) / Math.Sqrt(sqrSigmaNoise);
|
---|
409 | }
|
---|
410 | }
|
---|
411 |
|
---|
412 | // for stddev
|
---|
413 | alglib.ablas.rmatrixlefttrsm(n, newN, l, 0, 0, false, false, 0, ref sWKs, 0, 0);
|
---|
414 |
|
---|
415 | for (int i = 0; i < newN; i++) {
|
---|
416 | var col = Util.GetCol(sWKs, i).ToArray();
|
---|
417 | var sumV = Util.ScalarProd(col, col);
|
---|
418 | kss[i] += sqrSigmaNoise; // kss is V(f), add noise variance of predictive distibution to get V(y)
|
---|
419 | kss[i] -= sumV;
|
---|
420 | if (kss[i] < 0) kss[i] = 0;
|
---|
421 | }
|
---|
422 | return kss;
|
---|
423 | } catch (alglib.alglibexception ae) {
|
---|
424 | // wrap exception so that calling code doesn't have to know about alglib implementation
|
---|
425 | throw new ArgumentException("There was a problem in the calculation of the Gaussian process model", ae);
|
---|
426 | }
|
---|
427 | }
|
---|
428 |
|
---|
429 | }
|
---|
430 | }
|
---|