Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Algorithms.DataAnalysis/3.4/GaussianProcess/GaussianProcessModel.cs @ 8430

Last change on this file since 8430 was 8416, checked in by gkronber, 12 years ago

#1902 worked on sum and product covariance functions and fixed a few bugs.

File size: 9.5 KB
Line 
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
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.Problems.DataAnalysis;
29
30namespace 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 scaling;
76
77
78    [StorableConstructor]
79    private GaussianProcessModel(bool deserializing) : base(deserializing) { }
80    private GaussianProcessModel(GaussianProcessModel original, Cloner cloner)
81      : base(original, cloner) {
82      this.meanFunction = cloner.Clone(original.meanFunction);
83      this.covarianceFunction = cloner.Clone(original.covarianceFunction);
84      this.scaling = cloner.Clone(original.scaling);
85      this.negativeLogLikelihood = original.negativeLogLikelihood;
86      this.targetVariable = original.targetVariable;
87      this.sqrSigmaNoise = original.sqrSigmaNoise;
88
89      // shallow copies of arrays because they cannot be modified
90      this.allowedInputVariables = original.allowedInputVariables;
91      this.alpha = original.alpha;
92      this.l = original.l;
93      this.x = original.x;
94    }
95    public GaussianProcessModel(Dataset ds, string targetVariable, IEnumerable<string> allowedInputVariables, IEnumerable<int> rows,
96      IEnumerable<double> hyp, IMeanFunction meanFunction, ICovarianceFunction covarianceFunction)
97      : base() {
98      this.name = ItemName;
99      this.description = ItemDescription;
100      this.meanFunction = (IMeanFunction)meanFunction.Clone();
101      this.covarianceFunction = (ICovarianceFunction)covarianceFunction.Clone();
102      this.targetVariable = targetVariable;
103      this.allowedInputVariables = allowedInputVariables.ToArray();
104
105      sqrSigmaNoise = Math.Exp(2.0 * hyp.First());
106      sqrSigmaNoise = Math.Max(10E-6, sqrSigmaNoise); // lower limit for the noise level
107
108      int nVariables = this.allowedInputVariables.Length;
109      this.meanFunction.SetParameter(hyp.Skip(1)
110        .Take(this.meanFunction.GetNumberOfParameters(nVariables))
111        .ToArray());
112      this.covarianceFunction.SetParameter(hyp.Skip(1 + this.meanFunction.GetNumberOfParameters(nVariables))
113        .Take(this.covarianceFunction.GetNumberOfParameters(nVariables))
114        .ToArray());
115
116      CalculateModel(ds, rows);
117    }
118
119    private void CalculateModel(Dataset ds, IEnumerable<int> rows) {
120      scaling = new Scaling(ds, allowedInputVariables, rows);
121      x = AlglibUtil.PrepareAndScaleInputMatrix(ds, allowedInputVariables, rows, scaling);
122
123      var y = ds.GetDoubleValues(targetVariable, rows).ToArray();
124
125      int n = x.GetLength(0);
126      l = new double[n, n];
127
128      meanFunction.SetData(x);
129      covarianceFunction.SetData(x);
130
131      // calculate means and covariances
132      double[] m = meanFunction.GetMean(x);
133      for (int i = 0; i < n; i++) {
134
135        for (int j = i; j < n; j++) {
136          l[j, i] = covarianceFunction.GetCovariance(i, j) / sqrSigmaNoise;
137          if (j == i) l[j, i] += 1.0;
138        }
139      }
140
141      // cholesky decomposition
142      int info;
143      alglib.densesolverreport denseSolveRep;
144
145      var res = alglib.trfac.spdmatrixcholesky(ref l, n, false);
146      if (!res) throw new InvalidOperationException("Matrix is not positive semidefinite");
147
148      // calculate sum of diagonal elements for likelihood
149      double diagSum = Enumerable.Range(0, n).Select(i => Math.Log(l[i, i])).Sum();
150
151      // solve for alpha
152      double[] ym = y.Zip(m, (a, b) => a - b).ToArray();
153
154      alglib.spdmatrixcholeskysolve(l, n, false, ym, out info, out denseSolveRep, out alpha);
155      for (int i = 0; i < alpha.Length; i++)
156        alpha[i] = alpha[i] / sqrSigmaNoise;
157      negativeLogLikelihood = 0.5 * Util.ScalarProd(ym, alpha) + diagSum + (n / 2.0) * Math.Log(2.0 * Math.PI * sqrSigmaNoise);
158    }
159
160    public double[] GetHyperparameterGradients() {
161      // derivatives
162      int n = x.GetLength(0);
163      int nAllowedVariables = x.GetLength(1);
164      double[,] q = new double[n, n];
165      double[,] eye = new double[n, n];
166      for (int i = 0; i < n; i++) eye[i, i] = 1.0;
167
168      int info;
169      alglib.densesolverreport denseSolveRep;
170
171      alglib.spdmatrixcholeskysolvem(l, n, false, eye, n, out info, out denseSolveRep, out q);
172      // double[,] a2 = outerProd(alpha, alpha);
173      for (int i = 0; i < n; i++) {
174        for (int j = 0; j < n; j++)
175          q[i, j] = q[i, j] / sqrSigmaNoise - alpha[i] * alpha[j]; // a2[i, j];
176      }
177
178      double noiseGradient = sqrSigmaNoise * Enumerable.Range(0, n).Select(i => q[i, i]).Sum();
179
180      double[] meanGradients = new double[meanFunction.GetNumberOfParameters(nAllowedVariables)];
181      for (int i = 0; i < meanGradients.Length; i++) {
182        var meanGrad = meanFunction.GetGradients(i, x);
183        meanGradients[i] = -Util.ScalarProd(meanGrad, alpha);
184      }
185
186      double[] covGradients = new double[covarianceFunction.GetNumberOfParameters(nAllowedVariables)];
187      if (covGradients.Length > 0) {
188        for (int i = 0; i < n; i++) {
189          for (int j = 0; j < n; j++) {
190            var covDeriv = covarianceFunction.GetGradient(i, j);
191            for (int k = 0; k < covGradients.Length; k++) {
192              covGradients[k] += q[i, j] * covDeriv[k];
193            }
194          }
195        }
196        covGradients = covGradients.Select(g => g / 2.0).ToArray();
197      }
198
199      return new double[] { noiseGradient }
200        .Concat(meanGradients)
201        .Concat(covGradients).ToArray();
202    }
203
204
205    public override IDeepCloneable Clone(Cloner cloner) {
206      return new GaussianProcessModel(this, cloner);
207    }
208
209    #region IRegressionModel Members
210    public IEnumerable<double> GetEstimatedValues(Dataset dataset, IEnumerable<int> rows) {
211      return GetEstimatedValuesHelper(dataset, rows);
212    }
213    public GaussianProcessRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
214      return new GaussianProcessRegressionSolution(this, problemData);
215    }
216    IRegressionSolution IRegressionModel.CreateRegressionSolution(IRegressionProblemData problemData) {
217      return CreateRegressionSolution(problemData);
218    }
219    #endregion
220
221    private IEnumerable<double> GetEstimatedValuesHelper(Dataset dataset, IEnumerable<int> rows) {
222      var newX = AlglibUtil.PrepareAndScaleInputMatrix(dataset, allowedInputVariables, rows, scaling);
223      int newN = newX.GetLength(0);
224      int n = x.GetLength(0);
225      // var predMean = new double[newN];
226      // predVar = new double[newN];
227
228
229
230      // var kss = new double[newN];
231      var Ks = new double[newN, n];
232      double[,] sWKs = new double[n, newN];
233      // double[,] v;
234
235
236      // for stddev
237      //covarianceFunction.SetParameter(covHyp, newX);
238      //kss = covarianceFunction.GetDiagonalCovariances();
239
240      covarianceFunction.SetData(x, newX);
241      meanFunction.SetData(newX);
242      var ms = meanFunction.GetMean(newX);
243      for (int i = 0; i < newN; i++) {
244
245        for (int j = 0; j < n; j++) {
246          Ks[i, j] = covarianceFunction.GetCovariance(j, i);
247          sWKs[j, i] = Ks[i, j] / Math.Sqrt(sqrSigmaNoise);
248        }
249      }
250
251      // for stddev
252      // alglib.rmatrixsolvem(l, n, sWKs, newN, true, out info, out denseSolveRep, out v);
253
254
255      for (int i = 0; i < newN; i++) {
256        // predMean[i] = ms[i] + prod(GetRow(Ks, i), alpha);
257        yield return ms[i] + Util.ScalarProd(Util.GetRow(Ks, i), alpha);
258        // var sumV2 = prod(GetCol(v, i), GetCol(v, i));
259        // predVar[i] = kss[i] - sumV2;
260      }
261
262    }
263  }
264}
Note: See TracBrowser for help on using the repository browser.