Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Algorithms.DataAnalysis/3.4/GaussianProcess/GaussianProcessModel.cs @ 14166

Last change on this file since 14166 was 14166, checked in by mkommend, 8 years ago

#2597: Merged r14095, r14096, r14098, r14099, r14118, r14119, r14131, r14157, r14158 into stable.

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