Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/LinearRegression.cs @ 6002

Last change on this file since 6002 was 6002, checked in by gkronber, 13 years ago

#790 Fixed minor issues in LDA, LR, SVC and SVR to make sure everything works correctly in presence of NaN and infinity values.

File size: 5.6 KB
RevLine 
[5617]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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;
[5777]23using System.Collections.Generic;
[5617]24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
[5777]28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[5617]29using HeuristicLab.Optimization;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32using HeuristicLab.Problems.DataAnalysis.Symbolic;
[5624]33using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
[5617]34
35namespace HeuristicLab.Algorithms.DataAnalysis {
36  /// <summary>
37  /// Linear regression data analysis algorithm.
38  /// </summary>
39  [Item("Linear Regression", "Linear regression data analysis algorithm.")]
40  [Creatable("Data Analysis")]
41  [StorableClass]
42  public sealed class LinearRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
[5649]43    private const string LinearRegressionModelResultName = "Linear regression solution";
[5617]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() {
[5649]52      Problem = new RegressionProblem();
[5617]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() {
63      double rmsError, cvRmsError;
[5624]64      var solution = CreateLinearRegressionSolution(Problem.ProblemData, out rmsError, out cvRmsError);
[5649]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)));
[5617]68    }
69
[5624]70    public static ISymbolicRegressionSolution CreateLinearRegressionSolution(IRegressionProblemData problemData, out double rmsError, out double cvRmsError) {
71      Dataset dataset = problemData.Dataset;
72      string targetVariable = problemData.TargetVariable;
[5649]73      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
[5759]74      int samplesStart = problemData.TrainingPartition.Start;
75      int samplesEnd = problemData.TrainingPartition.End;
[5658]76      IEnumerable<int> rows = Enumerable.Range(samplesStart, samplesEnd - samplesStart);
77      double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows);
[6002]78      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
79        throw new NotSupportedException("Linear regression does not support NaN or infinity values in the input dataset.");
[5617]80
81      alglib.linearmodel lm = new alglib.linearmodel();
82      alglib.lrreport ar = new alglib.lrreport();
83      int nRows = inputMatrix.GetLength(0);
84      int nFeatures = inputMatrix.GetLength(1) - 1;
85      double[] coefficients = new double[nFeatures + 1]; // last coefficient is for the constant
86
87      int retVal = 1;
88      alglib.lrbuild(inputMatrix, nRows, nFeatures, out retVal, out lm, out ar);
[5649]89      if (retVal != 1) throw new ArgumentException("Error in calculation of linear regression solution");
[5617]90      rmsError = ar.rmserror;
91      cvRmsError = ar.cvrmserror;
92
93      alglib.lrunpack(lm, out coefficients, out nFeatures);
94
95      ISymbolicExpressionTree tree = new SymbolicExpressionTree(new ProgramRootSymbol().CreateTreeNode());
96      ISymbolicExpressionTreeNode startNode = new StartSymbol().CreateTreeNode();
[5733]97      tree.Root.AddSubtree(startNode);
[5617]98      ISymbolicExpressionTreeNode addition = new Addition().CreateTreeNode();
[5733]99      startNode.AddSubtree(addition);
[5617]100
101      int col = 0;
102      foreach (string column in allowedInputVariables) {
103        VariableTreeNode vNode = (VariableTreeNode)new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
104        vNode.VariableName = column;
105        vNode.Weight = coefficients[col];
[5733]106        addition.AddSubtree(vNode);
[5617]107        col++;
108      }
109
110      ConstantTreeNode cNode = (ConstantTreeNode)new Constant().CreateTreeNode();
111      cNode.Value = coefficients[coefficients.Length - 1];
[5733]112      addition.AddSubtree(cNode);
[5617]113
[5624]114      SymbolicRegressionSolution solution = new SymbolicRegressionSolution(new SymbolicRegressionModel(tree, new SymbolicDataAnalysisExpressionTreeInterpreter()), problemData);
115      return solution;
[5617]116    }
117    #endregion
118  }
119}
Note: See TracBrowser for help on using the repository browser.