Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RBFRegression/HeuristicLab.Algorithms.DataAnalysis/3.4/KernelRidgeRegression/KernelRidgeRegressionModel.cs @ 14891

Last change on this file since 14891 was 14891, checked in by bwerth, 7 years ago

#2699 reworked kenel functions (beta is always a scaling factor now), added LU-Decomposition as a fall-back if Cholesky-decomposition fails

File size: 9.1 KB
Line 
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
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.KernelRidgeRegression {
31  [StorableClass]
32  [Item("KernelRidgeRegressionModel", "A kernel ridge regression model")]
33  public sealed class KernelRidgeRegressionModel : RegressionModel {
34    public override IEnumerable<string> VariablesUsedForPrediction
35    {
36      get { return allowedInputVariables; }
37    }
38
39    [Storable]
40    private readonly string[] allowedInputVariables;
41    public string[] AllowedInputVariables
42    {
43      get { return allowedInputVariables; }
44    }
45
46
47    [Storable]
48    public double LooCvRMSE { get; private set; }
49
50    [Storable]
51    private readonly double[] alpha;
52
53    [Storable]
54    private readonly double[,] trainX; // it is better to store the original training dataset completely because this is more efficient in persistence
55
56    [Storable]
57    private readonly ITransformation<double>[] scaling;
58
59    [Storable]
60    private readonly ICovarianceFunction kernel;
61
62    [Storable]
63    private readonly double lambda;
64
65    [Storable]
66    private readonly double yOffset; // implementation works for zero-mean, unit-variance target variables
67
68    [Storable]
69    private readonly double yScale;
70
71    [StorableConstructor]
72    private KernelRidgeRegressionModel(bool deserializing) : base(deserializing) { }
73    private KernelRidgeRegressionModel(KernelRidgeRegressionModel original, Cloner cloner)
74      : base(original, cloner) {
75      // shallow copies of arrays because they cannot be modified
76      allowedInputVariables = original.allowedInputVariables;
77      alpha = original.alpha;
78      trainX = original.trainX;
79      scaling = original.scaling;
80      lambda = original.lambda;
81      LooCvRMSE = original.LooCvRMSE;
82
83      yOffset = original.yOffset;
84      yScale = original.yScale;
85      if (original.kernel != null)
86        kernel = cloner.Clone(original.kernel);
87    }
88    public override IDeepCloneable Clone(Cloner cloner) {
89      return new KernelRidgeRegressionModel(this, cloner);
90    }
91
92    public KernelRidgeRegressionModel(IDataset dataset, string targetVariable, IEnumerable<string> allowedInputVariables, IEnumerable<int> rows,
93      bool scaleInputs, ICovarianceFunction kernel, double lambda = 0.1) : base(targetVariable) {
94      if (kernel.GetNumberOfParameters(allowedInputVariables.Count()) > 0) throw new ArgumentException("All parameters in the kernel function must be specified.");
95      name = ItemName;
96      description = ItemDescription;
97      this.allowedInputVariables = allowedInputVariables.ToArray();
98      var trainingRows = rows.ToArray();
99      this.kernel = (ICovarianceFunction)kernel.Clone();
100      this.lambda = lambda;
101      try {
102        if (scaleInputs)
103          scaling = CreateScaling(dataset, trainingRows);
104        trainX = ExtractData(dataset, trainingRows, scaling);
105        var y = dataset.GetDoubleValues(targetVariable, trainingRows).ToArray();
106        yOffset = y.Average();
107        yScale = 1.0 / y.StandardDeviation();
108        for (int i = 0; i < y.Length; i++) {
109          y[i] -= yOffset;
110          y[i] *= yScale;
111        }
112        int info;
113        int n = trainX.GetLength(0);
114        alglib.densesolverreport denseSolveRep;
115        var gram = BuildGramMatrix(trainX, lambda);
116        var l = new double[n, n]; Array.Copy(gram, l, l.Length);
117
118        double[,] invG;
119        // cholesky decomposition
120        var res = alglib.trfac.spdmatrixcholesky(ref l, n, false);
121        if (res == false) { //throw new ArgumentException("Could not decompose matrix. Is it quadratic symmetric positive definite?");
122          int[] pivots;
123          var lua = new double[n, n];
124          Array.Copy(gram, lua, lua.Length);
125          alglib.rmatrixlu(ref lua, n, n, out pivots);
126          alglib.rmatrixlusolve(lua, pivots, n, y, out info, out denseSolveRep, out alpha);
127          if (info != 1) throw new ArgumentException("Could not create model.");
128          alglib.matinvreport rep;
129          invG = lua;  // rename
130          alglib.rmatrixluinverse(ref invG, pivots, n, out info, out rep);
131          if (info != 1) throw new ArgumentException("Could not invert Gram matrix.");
132        } else {
133          alglib.spdmatrixcholeskysolve(l, n, false, y, out info, out denseSolveRep, out alpha);
134          if (info != 1) throw new ArgumentException("Could not create model.");
135          // for LOO-CV we need to build the inverse of the gram matrix
136          alglib.matinvreport rep;
137          invG = l;   // rename
138          alglib.spdmatrixcholeskyinverse(ref invG, n, false, out info, out rep);
139          if (info != 1) throw new ArgumentException("Could not invert Gram matrix.");
140        }
141
142        var ssqLooError = 0.0;
143        for (int i = 0; i < n; i++) {
144          var pred_i = Util.ScalarProd(Util.GetRow(gram, i).ToArray(), alpha);
145          var looPred_i = pred_i - alpha[i] / invG[i, i];
146          var error = (y[i] - looPred_i) / yScale;
147          ssqLooError += error * error;
148        }
149        LooCvRMSE = Math.Sqrt(ssqLooError / n);
150      }
151      catch (alglib.alglibexception ae) {
152        // wrap exception so that calling code doesn't have to know about alglib implementation
153        throw new ArgumentException("There was a problem in the calculation of the kernel ridge regression model", ae);
154      }
155    }
156
157
158    #region IRegressionModel Members
159    public override IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
160      var newX = ExtractData(dataset, rows, scaling);
161      var dim = newX.GetLength(1);
162      var cov = kernel.GetParameterizedCovarianceFunction(new double[0], Enumerable.Range(0, dim).ToArray());
163
164      var pred = new double[newX.GetLength(0)];
165      for (int i = 0; i < pred.Length; i++) {
166        double sum = 0.0;
167        for (int j = 0; j < alpha.Length; j++) {
168          sum += alpha[j] * cov.CrossCovariance(trainX, newX, j, i);
169        }
170        pred[i] = sum / yScale + yOffset;
171      }
172      return pred;
173    }
174    public override IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
175      return new RegressionSolution(this, new RegressionProblemData(problemData));
176    }
177    #endregion
178
179    #region helpers
180    private double[,] BuildGramMatrix(double[,] data, double lambda) {
181      var n = data.GetLength(0);
182      var dim = data.GetLength(1);
183      var cov = kernel.GetParameterizedCovarianceFunction(new double[0], Enumerable.Range(0, dim).ToArray());
184      var gram = new double[n, n];
185      // G = (K + λ I)
186      for (var i = 0; i < n; i++) {
187        for (var j = i; j < n; j++) {
188          gram[i, j] = gram[j, i] = cov.Covariance(data, i, j); // symmetric matrix
189        }
190        gram[i, i] += lambda;
191      }
192      return gram;
193    }
194
195    private ITransformation<double>[] CreateScaling(IDataset dataset, int[] rows) {
196      var trans = new ITransformation<double>[allowedInputVariables.Length];
197      int i = 0;
198      foreach (var variable in allowedInputVariables) {
199        var lin = new LinearTransformation(allowedInputVariables);
200        var max = dataset.GetDoubleValues(variable, rows).Max();
201        var min = dataset.GetDoubleValues(variable, rows).Min();
202        lin.Multiplier = 1.0 / (max - min);
203        lin.Addend = -min / (max - min);
204        trans[i] = lin;
205        i++;
206      }
207      return trans;
208    }
209
210    private double[,] ExtractData(IDataset dataset, IEnumerable<int> rows, ITransformation<double>[] scaling = null) {
211      double[][] variables;
212      if (scaling != null) {
213        variables =
214          allowedInputVariables.Select((var, i) => scaling[i].Apply(dataset.GetDoubleValues(var, rows)).ToArray())
215            .ToArray();
216      } else {
217        variables =
218        allowedInputVariables.Select(var => dataset.GetDoubleValues(var, rows).ToArray()).ToArray();
219      }
220      int n = variables.First().Length;
221      var res = new double[n, variables.Length];
222      for (int r = 0; r < n; r++)
223        for (int c = 0; c < variables.Length; c++) {
224          res[r, c] = variables[c][r];
225        }
226      return res;
227    }
228    #endregion
229  }
230}
Note: See TracBrowser for help on using the repository browser.