Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveHiveEngine/HeuristicLab.Algorithms.DataAnalysis/3.4/NeuralNetwork/NeuralNetworkRegression.cs @ 13180

Last change on this file since 13180 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

File size: 11.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32using HeuristicLab.Problems.DataAnalysis.Symbolic;
33using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
34using HeuristicLab.Parameters;
35
36namespace HeuristicLab.Algorithms.DataAnalysis {
37  /// <summary>
38  /// Neural network regression data analysis algorithm.
39  /// </summary>
40  [Item("Neural Network Regression", "Neural network regression data analysis algorithm (wrapper for ALGLIB). Further documentation: http://www.alglib.net/dataanalysis/neuralnetworks.php")]
41  [Creatable("Data Analysis")]
42  [StorableClass]
43  public sealed class NeuralNetworkRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
44    private const string DecayParameterName = "Decay";
45    private const string HiddenLayersParameterName = "HiddenLayers";
46    private const string NodesInFirstHiddenLayerParameterName = "NodesInFirstHiddenLayer";
47    private const string NodesInSecondHiddenLayerParameterName = "NodesInSecondHiddenLayer";
48    private const string RestartsParameterName = "Restarts";
49    private const string NeuralNetworkRegressionModelResultName = "Neural network regression solution";
50
51    #region parameter properties
52    public IFixedValueParameter<DoubleValue> DecayParameter {
53      get { return (IFixedValueParameter<DoubleValue>)Parameters[DecayParameterName]; }
54    }
55    public ConstrainedValueParameter<IntValue> HiddenLayersParameter {
56      get { return (ConstrainedValueParameter<IntValue>)Parameters[HiddenLayersParameterName]; }
57    }
58    public IFixedValueParameter<IntValue> NodesInFirstHiddenLayerParameter {
59      get { return (IFixedValueParameter<IntValue>)Parameters[NodesInFirstHiddenLayerParameterName]; }
60    }
61    public IFixedValueParameter<IntValue> NodesInSecondHiddenLayerParameter {
62      get { return (IFixedValueParameter<IntValue>)Parameters[NodesInSecondHiddenLayerParameterName]; }
63    }
64    public IFixedValueParameter<IntValue> RestartsParameter {
65      get { return (IFixedValueParameter<IntValue>)Parameters[RestartsParameterName]; }
66    }
67    #endregion
68
69    #region properties
70    public double Decay {
71      get { return DecayParameter.Value.Value; }
72      set {
73        if (value < 0.001 || value > 100) throw new ArgumentException("The decay parameter should be set to a value between 0.001 and 100.", "Decay");
74        DecayParameter.Value.Value = value;
75      }
76    }
77    public int HiddenLayers {
78      get { return HiddenLayersParameter.Value.Value; }
79      set {
80        if (value < 0 || value > 2) throw new ArgumentException("The number of hidden layers should be set to 0, 1, or 2.", "HiddenLayers");
81        HiddenLayersParameter.Value = (from v in HiddenLayersParameter.ValidValues
82                                       where v.Value == value
83                                       select v)
84                                      .Single();
85      }
86    }
87    public int NodesInFirstHiddenLayer {
88      get { return NodesInFirstHiddenLayerParameter.Value.Value; }
89      set {
90        if (value < 1) throw new ArgumentException("The number of nodes in the first hidden layer must be at least one.", "NodesInFirstHiddenLayer");
91        NodesInFirstHiddenLayerParameter.Value.Value = value;
92      }
93    }
94    public int NodesInSecondHiddenLayer {
95      get { return NodesInSecondHiddenLayerParameter.Value.Value; }
96      set {
97        if (value < 1) throw new ArgumentException("The number of nodes in the first second layer must be at least one.", "NodesInSecondHiddenLayer");
98        NodesInSecondHiddenLayerParameter.Value.Value = value;
99      }
100    }
101    public int Restarts {
102      get { return RestartsParameter.Value.Value; }
103      set {
104        if (value < 0) throw new ArgumentException("The number of restarts must be positive.", "Restarts");
105        RestartsParameter.Value.Value = value;
106      }
107    }
108    #endregion
109
110
111    [StorableConstructor]
112    private NeuralNetworkRegression(bool deserializing) : base(deserializing) { }
113    private NeuralNetworkRegression(NeuralNetworkRegression original, Cloner cloner)
114      : base(original, cloner) {
115      RegisterEventHandlers();
116    }
117    public NeuralNetworkRegression()
118      : base() {
119      var validHiddenLayerValues = new ItemSet<IntValue>(new IntValue[] {
120        (IntValue)new IntValue(0).AsReadOnly(),
121        (IntValue)new IntValue(1).AsReadOnly(),
122        (IntValue)new IntValue(2).AsReadOnly() });
123      var selectedHiddenLayerValue = (from v in validHiddenLayerValues
124                                      where v.Value == 1
125                                      select v)
126                                     .Single();
127      Parameters.Add(new FixedValueParameter<DoubleValue>(DecayParameterName, "The decay parameter for the training phase of the neural network. This parameter determines the strengh of regularization and should be set to a value between 0.001 (weak regularization) to 100 (very strong regularization). The correct value should be determined via cross-validation.", new DoubleValue(1)));
128      Parameters.Add(new ConstrainedValueParameter<IntValue>(HiddenLayersParameterName, "The number of hidden layers for the neural network (0, 1, or 2)", validHiddenLayerValues, selectedHiddenLayerValue));
129      Parameters.Add(new FixedValueParameter<IntValue>(NodesInFirstHiddenLayerParameterName, "The number of nodes in the first hidden layer. This value is not used if the number of hidden layers is zero.", new IntValue(10)));
130      Parameters.Add(new FixedValueParameter<IntValue>(NodesInSecondHiddenLayerParameterName, "The number of nodes in the second hidden layer. This value is not used if the number of hidden layers is zero or one.", new IntValue(10)));
131      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of restarts for learning.", new IntValue(2)));
132
133      RestartsParameter.Hidden = true;
134      NodesInSecondHiddenLayerParameter.Hidden = true;
135
136      RegisterEventHandlers();
137
138      Problem = new RegressionProblem();
139    }
140
141    private void RegisterEventHandlers() {
142      HiddenLayersParameter.Value.ValueChanged += HiddenLayersParameterValueValueChanged;
143      HiddenLayersParameter.ValueChanged += HiddenLayersParameterValueChanged;
144    }
145
146    [StorableHook(HookType.AfterDeserialization)]
147    private void AfterDeserialization() {
148      RegisterEventHandlers();
149    }
150
151    public override IDeepCloneable Clone(Cloner cloner) {
152      return new NeuralNetworkRegression(this, cloner);
153    }
154
155    private void HiddenLayersParameterValueChanged(object source, EventArgs e) {
156      HiddenLayersParameter.Value.ValueChanged += HiddenLayersParameterValueValueChanged;
157      HiddenLayersParameterValueValueChanged(this, EventArgs.Empty);
158    }
159
160    private void HiddenLayersParameterValueValueChanged(object source, EventArgs e) {
161      if (HiddenLayers == 0) {
162        NodesInFirstHiddenLayerParameter.Hidden = true;
163        NodesInSecondHiddenLayerParameter.Hidden = true;
164      } else if (HiddenLayers == 1) {
165        NodesInFirstHiddenLayerParameter.Hidden = false;
166        NodesInSecondHiddenLayerParameter.Hidden = true;
167      } else {
168        NodesInFirstHiddenLayerParameter.Hidden = false;
169        NodesInSecondHiddenLayerParameter.Hidden = false;
170      }
171    }
172
173
174    #region neural network
175    protected override void Run() {
176      double rmsError, avgRelError;
177      var solution = CreateNeuralNetworkRegressionSolution(Problem.ProblemData, HiddenLayers, NodesInFirstHiddenLayer, NodesInSecondHiddenLayer, Decay, Restarts, out rmsError, out avgRelError);
178      Results.Add(new Result(NeuralNetworkRegressionModelResultName, "The neural network regression solution.", solution));
179      Results.Add(new Result("Root mean square error", "The root of the mean of squared errors of the neural network regression solution on the training set.", new DoubleValue(rmsError)));
180      Results.Add(new Result("Average relative error", "The average of relative errors of the neural network regression solution on the training set.", new PercentValue(avgRelError)));
181    }
182
183    public static IRegressionSolution CreateNeuralNetworkRegressionSolution(IRegressionProblemData problemData, int nLayers, int nHiddenNodes1, int nHiddenNodes2, double decay, int restarts,
184      out double rmsError, out double avgRelError) {
185      Dataset dataset = problemData.Dataset;
186      string targetVariable = problemData.TargetVariable;
187      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
188      IEnumerable<int> rows = problemData.TrainingIndizes;
189      double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows);
190      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
191        throw new NotSupportedException("Neural network regression does not support NaN or infinity values in the input dataset.");
192
193      alglib.multilayerperceptron multiLayerPerceptron = null;
194      if (nLayers == 0) {
195        alglib.mlpcreate0(allowedInputVariables.Count(), 1, out multiLayerPerceptron);
196      } else if (nLayers == 1) {
197        alglib.mlpcreate1(allowedInputVariables.Count(), nHiddenNodes1, 1, out multiLayerPerceptron);
198      } else if (nLayers == 2) {
199        alglib.mlpcreate2(allowedInputVariables.Count(), nHiddenNodes1, nHiddenNodes2, 1, out multiLayerPerceptron);
200      } else throw new ArgumentException("Number of layers must be zero, one, or two.", "nLayers");
201      alglib.mlpreport rep;
202      int nRows = inputMatrix.GetLength(0);
203
204      int info;
205      // using mlptrainlm instead of mlptraines or mlptrainbfgs because only one parameter is necessary
206      alglib.mlptrainlm(multiLayerPerceptron, inputMatrix, nRows, decay, restarts, out info, out rep);
207      if (info != 2) throw new ArgumentException("Error in calculation of neural network regression solution");
208
209      rmsError = alglib.mlprmserror(multiLayerPerceptron, inputMatrix, nRows);
210      avgRelError = alglib.mlpavgrelerror(multiLayerPerceptron, inputMatrix, nRows);
211
212      return new NeuralNetworkRegressionSolution((IRegressionProblemData)problemData.Clone(), new NeuralNetworkModel(multiLayerPerceptron, targetVariable, allowedInputVariables));
213    }
214    #endregion
215  }
216}
Note: See TracBrowser for help on using the repository browser.