Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Algorithms.DataAnalysis/3.4/GaussianProcess/StudentTProcessModel.cs @ 13777

Last change on this file since 13777 was 13438, checked in by gkronber, 9 years ago

#2541: added crude implementation of Student-t process (using almost the same source code as GP model)

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