source: branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/NeuralNetwork/NeuralNetworkRegression.cs @ 14542

Last change on this file since 14542 was 14542, checked in by gkronber, 3 years ago

#2650: merged r14504:14533 from trunk to branch

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