Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.ArtificialNeuralNetworks/3.2/MultiLayerPerceptronRegressionOperator.cs @ 2867

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

Added project for ANN. #751 (Plugin for for data-modeling with ANN (integrated into CEDMA))

File size: 9.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.Modeling;
29
30namespace HeuristicLab.ArtificialNeuralNetworks {
31  public class MultiLayerPerceptronRegressionOperator : OperatorBase {
32
33    public MultiLayerPerceptronRegressionOperator() {
34      AddVariableInfo(new VariableInfo("TargetVariable", "Name of the target variable", typeof(StringData), VariableKind.In));
35      AddVariableInfo(new VariableInfo("Dataset", "Dataset with all samples on which to apply the function", typeof(Dataset), VariableKind.In));
36      AddVariableInfo(new VariableInfo("SamplesStart", "Start index of samples in dataset to evaluate", typeof(IntData), VariableKind.In));
37      AddVariableInfo(new VariableInfo("SamplesEnd", "End index of samples in dataset to evaluate", typeof(IntData), VariableKind.In));
38      AddVariableInfo(new VariableInfo("NumberOfHiddenLayerNeurons", "The number of nodes in the hidden layer.", typeof(IntData), VariableKind.In));
39      AddVariableInfo(new VariableInfo("MaxTimeOffset", "(optional) Maximal time offset for time-series prognosis", typeof(IntData), VariableKind.In));
40      AddVariableInfo(new VariableInfo("MinTimeOffset", "(optional) Minimal time offset for time-series prognosis", typeof(IntData), VariableKind.In));
41      AddVariableInfo(new VariableInfo("MultiLayerPerceptron", "Formula that was calculated by multi layer perceptron regression", typeof(MultiLayerPerceptron), VariableKind.Out | VariableKind.New));
42    }
43
44    public override IOperation Apply(IScope scope) {
45      Dataset dataset = GetVariableValue<Dataset>("Dataset", scope, true);
46      string targetVariable = GetVariableValue<StringData>("TargetVariable", scope, true).Data;
47      int targetVariableIndex = dataset.GetVariableIndex(targetVariable);
48      int start = GetVariableValue<IntData>("SamplesStart", scope, true).Data;
49      int end = GetVariableValue<IntData>("SamplesEnd", scope, true).Data;
50      IntData maxTimeOffsetData = GetVariableValue<IntData>("MaxTimeOffset", scope, true, false);
51      int maxTimeOffset = maxTimeOffsetData == null ? 0 : maxTimeOffsetData.Data;
52      IntData minTimeOffsetData = GetVariableValue<IntData>("MinTimeOffset", scope, true, false);
53      int minTimeOffset = minTimeOffsetData == null ? 0 : minTimeOffsetData.Data;
54      int nHiddenNodes = GetVariableValue<IntData>("NumberOfHiddenLayerNeurons", scope, true).Data;
55
56      var perceptron = CreateModel(dataset, targetVariable, dataset.VariableNames, start, end, minTimeOffset, maxTimeOffset, nHiddenNodes);
57      scope.AddVariable(new HeuristicLab.Core.Variable(scope.TranslateName("MultiLayerPerceptron"), perceptron));
58      return null;
59    }
60
61    public static MultiLayerPerceptron CreateModel(Dataset dataset, string targetVariable, IEnumerable<string> inputVariables, int start, int end, int nHiddenNodes) {
62      return CreateModel(dataset, targetVariable, inputVariables, start, end, 0, 0, nHiddenNodes);
63    }
64
65    public static MultiLayerPerceptron CreateModel(Dataset dataset, string targetVariable, IEnumerable<string> inputVariables,
66        int start, int end,
67        int minTimeOffset, int maxTimeOffset, int nHiddenNodes) {
68      int targetVariableIndex = dataset.GetVariableIndex(targetVariable);
69      List<int> allowedColumns = CalculateAllowedColumns(dataset, targetVariableIndex, inputVariables.Select(x => dataset.GetVariableIndex(x)), start, end);
70      List<int> allowedRows = CalculateAllowedRows(dataset, targetVariableIndex, allowedColumns, start, end, minTimeOffset, maxTimeOffset);
71
72      double[,] inputMatrix = PrepareInputMatrix(dataset, allowedColumns, allowedRows, minTimeOffset, maxTimeOffset);
73      double[] targetVector = PrepareTargetVector(dataset, targetVariableIndex, allowedRows);
74
75      var perceptron = TrainPerceptron(inputMatrix, targetVector, nHiddenNodes);
76      return new MultiLayerPerceptron(perceptron, inputVariables, minTimeOffset, maxTimeOffset);
77    }
78
79
80
81    private static alglib.mlpbase.multilayerperceptron TrainPerceptron(double[,] inputMatrix, double[] targetVector, int nHiddenNodes) {
82      int retVal = 0;
83      int n = targetVector.Length;
84      int p = inputMatrix.GetLength(1);
85      alglib.mlpbase.multilayerperceptron perceptron = new alglib.mlpbase.multilayerperceptron();
86      alglib.mlpbase.mlpcreate1(p - 1, nHiddenNodes, 1, ref perceptron);
87      alglib.mlptrain.mlpreport report = new alglib.mlptrain.mlpreport();
88      double[,] dataset = new double[n, p];
89      for (int row = 0; row < n; row++) {
90        for (int column = 0; column < p - 1; column++) {
91          dataset[row, column] = inputMatrix[row, column];
92        }
93        dataset[row, p - 1] = targetVector[row];
94      }
95      alglib.mlptrain.mlptrainlbfgs(ref perceptron, ref dataset, n, 0.001, 2, 0.01, 0, ref retVal, ref report);
96      if (retVal != 2) throw new ArgumentException("Error in training of multi layer perceptron");
97      return perceptron;
98    }
99
100    //returns list of valid row indexes (rows without NaN values)
101    private static List<int> CalculateAllowedRows(Dataset dataset, int targetVariable, IList<int> allowedColumns, int start, int end, int minTimeOffset, int maxTimeOffset) {
102      List<int> allowedRows = new List<int>();
103      bool add;
104      for (int row = start; row < end; row++) {
105        add = true;
106        for (int colIndex = 0; colIndex < allowedColumns.Count && add == true; colIndex++) {
107          for (int timeOffset = minTimeOffset; timeOffset <= maxTimeOffset; timeOffset++) {
108            if (
109              row + timeOffset < 0 ||
110              row + timeOffset > dataset.Rows ||
111              double.IsNaN(dataset.GetValue(row + timeOffset, allowedColumns[colIndex])) ||
112              double.IsInfinity(dataset.GetValue(row + timeOffset, allowedColumns[colIndex])) ||
113              double.IsNaN(dataset.GetValue(row + timeOffset, targetVariable))) {
114              add = false;
115            }
116          }
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 max. 10% NaN (or infinity) and contain at least two different values)
126    private static List<int> CalculateAllowedColumns(Dataset dataset, int targetVariable, IEnumerable<int> inputVariables, int start, int end) {
127      List<int> allowedColumns = new List<int>();
128      double n = end - start;
129      foreach (int inputVariable in inputVariables) {// = 0; i < dataset.Columns; i++) {
130        double nanRatio = dataset.CountMissingValues(inputVariable, start, end) / n;
131        if (inputVariable != targetVariable && nanRatio < 0.1 && dataset.GetRange(inputVariable, start, end) > 0.0) {
132          allowedColumns.Add(inputVariable);
133        }
134      }
135      return allowedColumns;
136    }
137
138    private static double[,] PrepareInputMatrix(Dataset dataset, List<int> allowedColumns, List<int> allowedRows, int minTimeOffset, int maxTimeOffset) {
139      int rowCount = allowedRows.Count;
140      int timeOffsetRange = (maxTimeOffset - minTimeOffset + 1);
141      double[,] matrix = new double[rowCount, (allowedColumns.Count * timeOffsetRange) + 1];
142      for (int row = 0; row < allowedRows.Count; row++)
143        for (int col = 0; col < allowedColumns.Count; col++) {
144          for (int timeOffset = minTimeOffset; timeOffset <= maxTimeOffset; timeOffset++)
145            matrix[row, (col * timeOffsetRange) + (timeOffset - minTimeOffset)] = dataset.GetValue(allowedRows[row] + timeOffset, allowedColumns[col]);
146        }
147      //add constant 1.0 in last column
148      for (int i = 0; i < rowCount; i++)
149        matrix[i, allowedColumns.Count * timeOffsetRange] = 1.0;
150      return matrix;
151    }
152
153    private static double[] PrepareTargetVector(Dataset dataset, int targetVariable, List<int> allowedRows) {
154      int rowCount = allowedRows.Count;
155      double[] targetVector = new double[rowCount];
156      double[] samples = dataset.Samples;
157      for (int row = 0; row < rowCount; row++) {
158        targetVector[row] = dataset.GetValue(allowedRows[row], targetVariable);
159      }
160      return targetVector;
161    }
162  }
163}
Note: See TracBrowser for help on using the repository browser.