Free cookie consent management tool by TermsFeed Policy Generator

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

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

Merged changes from GP-refactoring branch back into the trunk #713.

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