Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2965_CancelablePersistence/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/LinearRegression.cs @ 16654

Last change on this file since 16654 was 16433, checked in by pfleck, 6 years ago

#2965 Merged recent trunk changes.
Enabled the prepared hooks that allows to cancel the save file using the recently introduced cancelable progressbars (in FileManager).

File size: 7.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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 System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Optimization;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32using HeuristicLab.Problems.DataAnalysis.Symbolic;
33using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
34
35namespace HeuristicLab.Algorithms.DataAnalysis {
36  /// <summary>
37  /// Linear regression data analysis algorithm.
38  /// </summary>
39  [Item("Linear Regression (LR)", "Linear regression data analysis algorithm (wrapper for ALGLIB).")]
40  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 100)]
41  [StorableClass]
42  public sealed class LinearRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
43    private const string LinearRegressionModelResultName = "Linear regression solution";
44
45    [StorableConstructor]
46    private LinearRegression(bool deserializing) : base(deserializing) { }
47    private LinearRegression(LinearRegression original, Cloner cloner)
48      : base(original, cloner) {
49    }
50    public LinearRegression()
51      : base() {
52      Problem = new RegressionProblem();
53    }
54    [StorableHook(HookType.AfterDeserialization)]
55    private void AfterDeserialization() { }
56
57    public override IDeepCloneable Clone(Cloner cloner) {
58      return new LinearRegression(this, cloner);
59    }
60
61    #region linear regression
62    protected override void Run(CancellationToken cancellationToken) {
63      double rmsError, cvRmsError;
64      var solution = CreateSolution(Problem.ProblemData, out rmsError, out cvRmsError);
65      Results.Add(new Result(LinearRegressionModelResultName, "The linear regression solution.", solution));
66      Results.Add(new Result("Root mean square error", "The root of the mean of squared errors of the linear regression solution on the training set.", new DoubleValue(rmsError)));
67      Results.Add(new Result("Estimated root mean square error (cross-validation)", "The estimated root of the mean of squared errors of the linear regression solution via cross validation.", new DoubleValue(cvRmsError)));
68    }
69
70    [Obsolete("Use CreateSolution() instead")]
71    public static ISymbolicRegressionSolution CreateLinearRegressionSolution(IRegressionProblemData problemData, out double rmsError, out double cvRmsError) {
72      IEnumerable<string> doubleVariables;
73      IEnumerable<KeyValuePair<string, IEnumerable<string>>> factorVariables;
74      double[,] inputMatrix;
75      PrepareData(problemData, out inputMatrix, out doubleVariables, out factorVariables);
76
77      alglib.linearmodel lm = new alglib.linearmodel();
78      alglib.lrreport ar = new alglib.lrreport();
79      int nRows = inputMatrix.GetLength(0);
80      int nFeatures = inputMatrix.GetLength(1) - 1;
81
82      int retVal = 1;
83      alglib.lrbuild(inputMatrix, nRows, nFeatures, out retVal, out lm, out ar);
84      if (retVal != 1) throw new ArgumentException("Error in calculation of linear regression solution");
85      rmsError = ar.rmserror;
86      cvRmsError = ar.cvrmserror;
87
88      double[] coefficients = new double[nFeatures + 1]; // last coefficient is for the constant
89      alglib.lrunpack(lm, out coefficients, out nFeatures);
90     
91      int nFactorCoeff = factorVariables.Sum(kvp=>kvp.Value.Count());
92      int nVarCoeff = doubleVariables.Count();
93      var tree = LinearModelToTreeConverter.CreateTree(factorVariables, coefficients.Take(nFactorCoeff).ToArray(),
94        doubleVariables.ToArray(), coefficients.Skip(nFactorCoeff).Take(nVarCoeff).ToArray(),
95        @const: coefficients[nFeatures]);
96
97      SymbolicRegressionSolution solution = new SymbolicRegressionSolution(new SymbolicRegressionModel(problemData.TargetVariable, tree, new SymbolicDataAnalysisExpressionTreeLinearInterpreter()), (IRegressionProblemData)problemData.Clone());
98      solution.Model.Name = "Linear Regression Model";
99      solution.Name = "Linear Regression Solution";
100      return solution;
101    }
102
103    public static IRegressionSolution CreateSolution(IRegressionProblemData problemData, out double rmsError, out double cvRmsError) {
104      IEnumerable<string> doubleVariables;
105      IEnumerable<KeyValuePair<string, IEnumerable<string>>> factorVariables;
106      double[,] inputMatrix;
107      PrepareData(problemData, out inputMatrix, out doubleVariables, out factorVariables);
108
109      alglib.linearmodel lm = new alglib.linearmodel();
110      alglib.lrreport ar = new alglib.lrreport();
111      int nRows = inputMatrix.GetLength(0);
112      int nFeatures = inputMatrix.GetLength(1) - 1;
113
114      int retVal = 1;
115      alglib.lrbuild(inputMatrix, nRows, nFeatures, out retVal, out lm, out ar);
116      if (retVal != 1) throw new ArgumentException("Error in calculation of linear regression solution");
117      rmsError = ar.rmserror;
118      cvRmsError = ar.cvrmserror;
119
120      // get parameters of the model
121      double[] w;
122      int nVars;
123      alglib.lrunpack(lm, out w, out nVars);
124
125      // ar.c is the covariation matrix,  array[0..NVars,0..NVars].
126      // C[i, j] = Cov(A[i], A[j])
127
128      var solution = new LinearRegressionModel(w, ar.c, cvRmsError, problemData.TargetVariable, doubleVariables, factorVariables)
129        .CreateRegressionSolution((IRegressionProblemData)problemData.Clone());
130      solution.Name = "Linear Regression Solution";
131      return solution;
132    }
133
134    private static void PrepareData(IRegressionProblemData problemData,
135      out double[,] inputMatrix,
136      out IEnumerable<string> doubleVariables,
137      out IEnumerable<KeyValuePair<string, IEnumerable<string>>> factorVariables) {
138      var dataset = problemData.Dataset;
139      string targetVariable = problemData.TargetVariable;
140      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
141      IEnumerable<int> rows = problemData.TrainingIndices;
142      doubleVariables = allowedInputVariables.Where(dataset.VariableHasType<double>);
143      var factorVariableNames = allowedInputVariables.Where(dataset.VariableHasType<string>);
144      factorVariables = dataset.GetFactorVariableValues(factorVariableNames, rows);
145      double[,] binaryMatrix = dataset.ToArray(factorVariables, rows);
146      double[,] doubleVarMatrix = dataset.ToArray(doubleVariables.Concat(new string[] { targetVariable }), rows);
147      inputMatrix = binaryMatrix.HorzCat(doubleVarMatrix);
148
149      if (inputMatrix.ContainsNanOrInfinity())
150        throw new NotSupportedException("Linear regression does not support NaN or infinity values in the input dataset.");
151    }
152    #endregion
153  }
154}
Note: See TracBrowser for help on using the repository browser.