Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 2196 was 2165, checked in by gkronber, 15 years ago

Removed variable AllowedFeatures in all modeling algorithms. #709

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