Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-Refactoring-713/sources/HeuristicLab.LinearRegression/3.2/LinearRegressionOperator.cs @ 2202

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

Created a branch for #713

File size: 7.7 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.Select(i => dataset.GetVariableName(i)).ToList());
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<string> allowedVariables) {
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        var vNode = new GP.StructureIdentification.Variable().GetTreeNode();
76        vNode.GetLocalVariable(GP.StructureIdentification.Variable.INDEX).Value = new StringData(allowedVariables[i]);
77        vNode.GetLocalVariable(GP.StructureIdentification.Variable.WEIGHT).Value = new DoubleData(coefficients[i]);
78        vNode.GetLocalVariable(GP.StructureIdentification.Variable.OFFSET).Value = new ConstrainedIntData(0);
79        nodes.Enqueue(vNode);
80      }
81      var cNode = new Constant().GetTreeNode();
82
83      cNode.GetLocalVariable(GP.StructureIdentification.Constant.VALUE).Value = new DoubleData(coefficients[coefficients.Length - 1]);
84      nodes.Enqueue(cNode);
85
86      IFunctionTree newTree;
87      while (nodes.Count != 1) {
88        newTree = new Addition().GetTreeNode();
89        newTree.AddSubTree(nodes.Dequeue());
90        newTree.AddSubTree(nodes.Dequeue());
91        nodes.Enqueue(newTree);
92      }
93
94      return nodes.Dequeue();
95    }
96
97    private double[] CalculateCoefficients(double[,] inputMatrix, double[] targetVector) {
98      double[] weights = new double[targetVector.Length];
99      double[] coefficients = new double[inputMatrix.GetLength(1)];
100      for (int i = 0; i < weights.Length; i++) weights[i] = 1.0;
101      // call external ALGLIB solver
102      leastsquares.buildgeneralleastsquares(ref targetVector, ref weights, ref inputMatrix, inputMatrix.GetLength(0), inputMatrix.GetLength(1), ref coefficients);
103
104      return coefficients;
105    }
106
107    //returns list of valid row indexes (rows without NaN values)
108    private List<int> CalculateAllowedRows(Dataset dataset, int targetVariable, int start, int end) {
109      List<int> allowedRows = new List<int>();
110      bool add;
111      for (int row = start; row < end; row++) {
112        add = true;
113        for (int col = 0; col < dataset.Columns && add == true; col++) {
114          if (double.IsNaN(dataset.GetValue(row, col)) ||
115              double.IsNaN(dataset.GetValue(row, targetVariable)))
116            add = false;
117        }
118        if (add)
119          allowedRows.Add(row);
120        add = true;
121      }
122      return allowedRows;
123    }
124
125    //returns list of valid column indexes (columns which contain at least one non-zero value)
126    private List<int> CalculateAllowedColumns(Dataset dataset, int targetVariable, int start, int end) {
127      List<int> allowedColumns = new List<int>();
128      for (int i = 0; i < dataset.Columns; i++) {
129        if (i == targetVariable) continue;
130        if (!IsAlmost(dataset.GetMinimum(i, start, end), 0.0) ||
131            !IsAlmost(dataset.GetMaximum(i, start, end), 0.0))
132          allowedColumns.Add(i);
133      }
134      return allowedColumns;
135    }
136
137    private double[,] PrepareInputMatrix(Dataset dataset, List<int> allowedColumns, List<int> allowedRows) {
138      int rowCount = allowedRows.Count;
139      double[,] matrix = new double[rowCount, allowedColumns.Count + 1];
140      for (int col = 0; col < allowedColumns.Count; col++) {
141        for (int row = 0; row < allowedRows.Count; row++)
142          matrix[row, col] = dataset.GetValue(allowedRows[row], allowedColumns[col]);
143      }
144      //add constant 1.0 in last column
145      for (int i = 0; i < rowCount; i++)
146        matrix[i, allowedColumns.Count] = constant;
147      return matrix;
148    }
149
150    private double[] PrepareTargetVector(Dataset dataset, int targetVariable, List<int> allowedRows) {
151      int rowCount = allowedRows.Count;
152      double[] targetVector = new double[rowCount];
153      double[] samples = dataset.Samples;
154      for (int row = 0; row < rowCount; row++) {
155        targetVector[row] = dataset.GetValue(allowedRows[row], targetVariable);
156      }
157      return targetVector;
158    }
159  }
160}
Note: See TracBrowser for help on using the repository browser.