Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.LinearRegression/3.2/LinearRegressionOperator.cs @ 2324

Last change on this file since 2324 was 2324, checked in by mkommend, 15 years ago

moved DoubleExtension to HeuristicLab.Common (ticket #733)

File size: 7.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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
21using System;
22using System.Collections.Generic;
23using System.Linq;
24using System.Text;
25using HeuristicLab.Core;
26using HeuristicLab.Common;
27using HeuristicLab.Data;
28using HeuristicLab.DataAnalysis;
29using HeuristicLab.Modeling;
30using HeuristicLab.GP;
31using HeuristicLab.GP.StructureIdentification;
32using HeuristicLab.GP.Interfaces;
33
34namespace HeuristicLab.LinearRegression {
35  public class LinearRegressionOperator : OperatorBase {
36    private static double constant = 1.0;
37
38    public LinearRegressionOperator() {
39      AddVariableInfo(new VariableInfo("TargetVariable", "Index of the column of the dataset that holds the target variable", typeof(IntData), VariableKind.In));
40      AddVariableInfo(new VariableInfo("Dataset", "Dataset with all samples on which to apply the function", typeof(Dataset), VariableKind.In));
41      AddVariableInfo(new VariableInfo("SamplesStart", "Start index of samples in dataset to evaluate", typeof(IntData), VariableKind.In));
42      AddVariableInfo(new VariableInfo("SamplesEnd", "End index of samples in dataset to evaluate", typeof(IntData), VariableKind.In));
43      AddVariableInfo(new VariableInfo("LinearRegressionModel", "Formula that was calculated by linear regression", typeof(IGeneticProgrammingModel), VariableKind.Out | VariableKind.New));
44    }
45
46    public override IOperation Apply(IScope scope) {
47      int targetVariable = GetVariableValue<IntData>("TargetVariable", scope, true).Data;
48      Dataset dataset = GetVariableValue<Dataset>("Dataset", scope, true);
49      int start = GetVariableValue<IntData>("SamplesStart", scope, true).Data;
50      int end = GetVariableValue<IntData>("SamplesEnd", scope, true).Data;
51      List<int> allowedRows = CalculateAllowedRows(dataset, targetVariable, start, end);
52      List<int> allowedColumns = CalculateAllowedColumns(dataset, targetVariable, start, end);
53
54      double[,] inputMatrix = PrepareInputMatrix(dataset, allowedColumns, allowedRows);
55      double[] targetVector = PrepareTargetVector(dataset, targetVariable, allowedRows);
56      double[] coefficients = CalculateCoefficients(inputMatrix, targetVector);
57      IFunctionTree tree = CreateModel(coefficients, allowedColumns.Select(i => dataset.GetVariableName(i)).ToList());
58
59      scope.AddVariable(new HeuristicLab.Core.Variable(scope.TranslateName("LinearRegressionModel"), new GeneticProgrammingModel(tree)));
60      return null;
61    }
62
63    private IFunctionTree CreateModel(double[] coefficients, List<string> allowedVariables) {
64      IFunctionTree root = new Addition().GetTreeNode();
65      IFunctionTree actNode = root;
66
67      Queue<IFunctionTree> nodes = new Queue<IFunctionTree>();
68      GP.StructureIdentification.Variable v;
69      for (int i = 0; i < coefficients.Length - 1; i++) {
70        var vNode = (VariableFunctionTree)new GP.StructureIdentification.Variable().GetTreeNode();
71        vNode.VariableName = allowedVariables[i];
72        vNode.Weight = coefficients[i];
73        vNode.SampleOffset = 0;
74        nodes.Enqueue(vNode);
75      }
76      var cNode = (ConstantFunctionTree)new Constant().GetTreeNode();
77
78      cNode.Value = coefficients[coefficients.Length - 1];
79      nodes.Enqueue(cNode);
80
81      IFunctionTree newTree;
82      while (nodes.Count != 1) {
83        newTree = new Addition().GetTreeNode();
84        newTree.AddSubTree(nodes.Dequeue());
85        newTree.AddSubTree(nodes.Dequeue());
86        nodes.Enqueue(newTree);
87      }
88
89      return nodes.Dequeue();
90    }
91
92    private double[] CalculateCoefficients(double[,] inputMatrix, double[] targetVector) {
93      double[] weights = new double[targetVector.Length];
94      double[] coefficients = new double[inputMatrix.GetLength(1)];
95      for (int i = 0; i < weights.Length; i++) weights[i] = 1.0;
96      // call external ALGLIB solver
97      leastsquares.buildgeneralleastsquares(ref targetVector, ref weights, ref inputMatrix, inputMatrix.GetLength(0), inputMatrix.GetLength(1), ref coefficients);
98
99      return coefficients;
100    }
101
102    //returns list of valid row indexes (rows without NaN values)
103    private List<int> CalculateAllowedRows(Dataset dataset, int targetVariable, int start, int end) {
104      List<int> allowedRows = new List<int>();
105      bool add;
106      for (int row = start; row < end; row++) {
107        add = true;
108        for (int col = 0; col < dataset.Columns && add == true; col++) {
109          if (double.IsNaN(dataset.GetValue(row, col)) ||
110              double.IsNaN(dataset.GetValue(row, targetVariable)))
111            add = false;
112        }
113        if (add)
114          allowedRows.Add(row);
115        add = true;
116      }
117      return allowedRows;
118    }
119
120    //returns list of valid column indexes (columns which contain at least one non-zero value)
121    private List<int> CalculateAllowedColumns(Dataset dataset, int targetVariable, int start, int end) {
122      List<int> allowedColumns = new List<int>();
123      for (int i = 0; i < dataset.Columns; i++) {
124        if (i == targetVariable) continue;
125        if (!dataset.GetMinimum(i, start, end).IsAlmost(0.0) ||
126            !dataset.GetMaximum(i, start, end).IsAlmost(0.0))
127          allowedColumns.Add(i);
128      }
129      return allowedColumns;
130    }
131
132    private double[,] PrepareInputMatrix(Dataset dataset, List<int> allowedColumns, List<int> allowedRows) {
133      int rowCount = allowedRows.Count;
134      double[,] matrix = new double[rowCount, allowedColumns.Count + 1];
135      for (int col = 0; col < allowedColumns.Count; col++) {
136        for (int row = 0; row < allowedRows.Count; row++)
137          matrix[row, col] = dataset.GetValue(allowedRows[row], allowedColumns[col]);
138      }
139      //add constant 1.0 in last column
140      for (int i = 0; i < rowCount; i++)
141        matrix[i, allowedColumns.Count] = constant;
142      return matrix;
143    }
144
145    private double[] PrepareTargetVector(Dataset dataset, int targetVariable, List<int> allowedRows) {
146      int rowCount = allowedRows.Count;
147      double[] targetVector = new double[rowCount];
148      double[] samples = dataset.Samples;
149      for (int row = 0; row < rowCount; row++) {
150        targetVector[row] = dataset.GetValue(allowedRows[row], targetVariable);
151      }
152      return targetVector;
153    }
154  }
155}
Note: See TracBrowser for help on using the repository browser.