[5617] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[17180] | 3 | * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[5617] | 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 |
|
---|
| 22 | using System;
|
---|
[5777] | 23 | using System.Collections.Generic;
|
---|
[5617] | 24 | using System.Linq;
|
---|
[14523] | 25 | using System.Threading;
|
---|
[5617] | 26 | using HeuristicLab.Common;
|
---|
| 27 | using HeuristicLab.Core;
|
---|
| 28 | using HeuristicLab.Data;
|
---|
| 29 | using HeuristicLab.Optimization;
|
---|
[16565] | 30 | using HEAL.Attic;
|
---|
[5617] | 31 | using HeuristicLab.Problems.DataAnalysis;
|
---|
| 32 | using HeuristicLab.Problems.DataAnalysis.Symbolic;
|
---|
[5624] | 33 | using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
|
---|
[17991] | 34 | using HeuristicLab.Analysis;
|
---|
| 35 | using HeuristicLab.Analysis.Statistics;
|
---|
[5617] | 36 |
|
---|
| 37 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
| 38 | /// <summary>
|
---|
| 39 | /// Linear regression data analysis algorithm.
|
---|
| 40 | /// </summary>
|
---|
[13238] | 41 | [Item("Linear Regression (LR)", "Linear regression data analysis algorithm (wrapper for ALGLIB).")]
|
---|
[12504] | 42 | [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 100)]
|
---|
[16565] | 43 | [StorableType("CF99D45E-F341-445E-9B9E-0587A8D9CBA7")]
|
---|
[5617] | 44 | public sealed class LinearRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
|
---|
[16448] | 45 | private const string SolutionResultName = "Linear regression solution";
|
---|
| 46 | private const string ConfidenceSolutionResultName = "Solution with prediction intervals";
|
---|
[5617] | 47 |
|
---|
| 48 | [StorableConstructor]
|
---|
[16565] | 49 | private LinearRegression(StorableConstructorFlag _) : base(_) { }
|
---|
[5617] | 50 | private LinearRegression(LinearRegression original, Cloner cloner)
|
---|
| 51 | : base(original, cloner) {
|
---|
| 52 | }
|
---|
| 53 | public LinearRegression()
|
---|
| 54 | : base() {
|
---|
[5649] | 55 | Problem = new RegressionProblem();
|
---|
[5617] | 56 | }
|
---|
| 57 | [StorableHook(HookType.AfterDeserialization)]
|
---|
| 58 | private void AfterDeserialization() { }
|
---|
| 59 |
|
---|
| 60 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 61 | return new LinearRegression(this, cloner);
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | #region linear regression
|
---|
[14523] | 65 | protected override void Run(CancellationToken cancellationToken) {
|
---|
[5617] | 66 | double rmsError, cvRmsError;
|
---|
[16448] | 67 | // produce both solutions, to allow symbolic manipulation of LR solutions as well
|
---|
| 68 | // as the calculation of prediction intervals.
|
---|
| 69 | // There is no clean way to implement the new model class for LR as a symbolic model.
|
---|
[17991] | 70 | var solution = CreateSolution(Problem.ProblemData, out rmsError, out cvRmsError, out _);
|
---|
[16448] | 71 | #pragma warning disable 168, 3021
|
---|
[17991] | 72 | var symbolicSolution = CreateLinearRegressionSolution(Problem.ProblemData, out rmsError, out cvRmsError, out var statistics);
|
---|
[16448] | 73 | #pragma warning restore 168, 3021
|
---|
| 74 | Results.Add(new Result(SolutionResultName, "The linear regression solution.", symbolicSolution));
|
---|
| 75 | Results.Add(new Result(ConfidenceSolutionResultName, "Linear regression solution with parameter covariance matrix " +
|
---|
| 76 | "and calculation of prediction intervals", solution));
|
---|
[5649] | 77 | 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)));
|
---|
| 78 | 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)));
|
---|
[17991] | 79 |
|
---|
| 80 | var predictorNames = Problem.ProblemData.AllowedInputVariables.Concat(new string[] { "<const>" }).ToArray();
|
---|
| 81 | Results.AddOrUpdateResult("Statistics", statistics.AsResultCollection(predictorNames));
|
---|
| 82 |
|
---|
[5617] | 83 | }
|
---|
| 84 |
|
---|
[16389] | 85 | [Obsolete("Use CreateSolution() instead")]
|
---|
[17991] | 86 | public static ISymbolicRegressionSolution CreateLinearRegressionSolution(IRegressionProblemData problemData, out double rmsError, out double cvRmsError, out Statistics statistics) {
|
---|
[16389] | 87 | IEnumerable<string> doubleVariables;
|
---|
| 88 | IEnumerable<KeyValuePair<string, IEnumerable<string>>> factorVariables;
|
---|
| 89 | double[,] inputMatrix;
|
---|
| 90 | PrepareData(problemData, out inputMatrix, out doubleVariables, out factorVariables);
|
---|
[14826] | 91 |
|
---|
[5617] | 92 | int nRows = inputMatrix.GetLength(0);
|
---|
| 93 | int nFeatures = inputMatrix.GetLength(1) - 1;
|
---|
| 94 |
|
---|
[17991] | 95 | alglib.lrbuild(inputMatrix, nRows, nFeatures, out int retVal, out var lm, out var ar);
|
---|
[5649] | 96 | if (retVal != 1) throw new ArgumentException("Error in calculation of linear regression solution");
|
---|
[5617] | 97 | rmsError = ar.rmserror;
|
---|
| 98 | cvRmsError = ar.cvrmserror;
|
---|
| 99 |
|
---|
[16389] | 100 | double[] coefficients = new double[nFeatures + 1]; // last coefficient is for the constant
|
---|
[5617] | 101 | alglib.lrunpack(lm, out coefficients, out nFeatures);
|
---|
[16448] | 102 |
|
---|
[17991] | 103 | // prepare inputmatrix (which has y as last column) for calculation of parameter statistics
|
---|
| 104 | // the last coefficient is the offset
|
---|
| 105 | var resid = new double[nRows];
|
---|
| 106 | for (int r = 0; r < nRows; r++) {
|
---|
| 107 | resid[r] = inputMatrix[r, nFeatures] - coefficients[nFeatures];
|
---|
| 108 | inputMatrix[r, nFeatures] = 1.0;
|
---|
| 109 | }
|
---|
| 110 | statistics = Statistics.CalculateParameterStatistics(inputMatrix, coefficients, resid);
|
---|
| 111 |
|
---|
[16448] | 112 | int nFactorCoeff = factorVariables.Sum(kvp => kvp.Value.Count());
|
---|
[14843] | 113 | int nVarCoeff = doubleVariables.Count();
|
---|
| 114 | var tree = LinearModelToTreeConverter.CreateTree(factorVariables, coefficients.Take(nFactorCoeff).ToArray(),
|
---|
[15783] | 115 | doubleVariables.ToArray(), coefficients.Skip(nFactorCoeff).Take(nVarCoeff).ToArray(),
|
---|
[14843] | 116 | @const: coefficients[nFeatures]);
|
---|
[15783] | 117 |
|
---|
[17991] | 118 | SymbolicRegressionSolution solution = new SymbolicRegressionSolution(
|
---|
| 119 | new SymbolicRegressionModel(problemData.TargetVariable, tree, new SymbolicDataAnalysisExpressionTreeLinearInterpreter(), parameterCovariance: statistics.CovMx),
|
---|
| 120 | (IRegressionProblemData)problemData.Clone());
|
---|
[6555] | 121 | solution.Model.Name = "Linear Regression Model";
|
---|
[7588] | 122 | solution.Name = "Linear Regression Solution";
|
---|
[5624] | 123 | return solution;
|
---|
[5617] | 124 | }
|
---|
[16389] | 125 |
|
---|
[17991] | 126 | public static IRegressionSolution CreateSolution(IRegressionProblemData problemData, out double rmsError, out double cvRmsError, out Statistics statistics) {
|
---|
[16389] | 127 | IEnumerable<string> doubleVariables;
|
---|
| 128 | IEnumerable<KeyValuePair<string, IEnumerable<string>>> factorVariables;
|
---|
| 129 | double[,] inputMatrix;
|
---|
| 130 | PrepareData(problemData, out inputMatrix, out doubleVariables, out factorVariables);
|
---|
| 131 |
|
---|
| 132 | int nRows = inputMatrix.GetLength(0);
|
---|
| 133 | int nFeatures = inputMatrix.GetLength(1) - 1;
|
---|
| 134 |
|
---|
[17991] | 135 | alglib.lrbuild(inputMatrix, nRows, nFeatures, out int retVal, out var lm, out var ar);
|
---|
[16389] | 136 | if (retVal != 1) throw new ArgumentException("Error in calculation of linear regression solution");
|
---|
| 137 | rmsError = ar.rmserror;
|
---|
| 138 | cvRmsError = ar.cvrmserror;
|
---|
| 139 |
|
---|
| 140 | // get parameters of the model
|
---|
| 141 | double[] w;
|
---|
[17991] | 142 | alglib.lrunpack(lm, out w, out _);
|
---|
[16389] | 143 |
|
---|
[17991] | 144 | // prepare inputmatrix (which has y as last column) for calculation of parameter statistics
|
---|
| 145 | // the last coefficient is the offset
|
---|
| 146 | var resid = new double[nRows];
|
---|
| 147 | for (int r = 0; r < nRows; r++) {
|
---|
| 148 | resid[r] = inputMatrix[r, nFeatures] - w[nFeatures];
|
---|
| 149 | inputMatrix[r, nFeatures] = 1.0;
|
---|
| 150 | }
|
---|
| 151 | statistics = Statistics.CalculateParameterStatistics(inputMatrix, w, resid);
|
---|
| 152 |
|
---|
[16389] | 153 | // ar.c is the covariation matrix, array[0..NVars,0..NVars].
|
---|
| 154 | var solution = new LinearRegressionModel(w, ar.c, cvRmsError, problemData.TargetVariable, doubleVariables, factorVariables)
|
---|
| 155 | .CreateRegressionSolution((IRegressionProblemData)problemData.Clone());
|
---|
| 156 | solution.Name = "Linear Regression Solution";
|
---|
| 157 | return solution;
|
---|
| 158 | }
|
---|
| 159 |
|
---|
[16448] | 160 | private static void PrepareData(IRegressionProblemData problemData,
|
---|
| 161 | out double[,] inputMatrix,
|
---|
| 162 | out IEnumerable<string> doubleVariables,
|
---|
[16389] | 163 | out IEnumerable<KeyValuePair<string, IEnumerable<string>>> factorVariables) {
|
---|
| 164 | var dataset = problemData.Dataset;
|
---|
| 165 | string targetVariable = problemData.TargetVariable;
|
---|
| 166 | IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
|
---|
| 167 | IEnumerable<int> rows = problemData.TrainingIndices;
|
---|
| 168 | doubleVariables = allowedInputVariables.Where(dataset.VariableHasType<double>);
|
---|
| 169 | var factorVariableNames = allowedInputVariables.Where(dataset.VariableHasType<string>);
|
---|
| 170 | factorVariables = dataset.GetFactorVariableValues(factorVariableNames, rows);
|
---|
| 171 | double[,] binaryMatrix = dataset.ToArray(factorVariables, rows);
|
---|
| 172 | double[,] doubleVarMatrix = dataset.ToArray(doubleVariables.Concat(new string[] { targetVariable }), rows);
|
---|
| 173 | inputMatrix = binaryMatrix.HorzCat(doubleVarMatrix);
|
---|
| 174 |
|
---|
| 175 | if (inputMatrix.ContainsNanOrInfinity())
|
---|
| 176 | throw new NotSupportedException("Linear regression does not support NaN or infinity values in the input dataset.");
|
---|
| 177 | }
|
---|
[5617] | 178 | #endregion
|
---|
| 179 | }
|
---|
| 180 | }
|
---|