Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Algorithms.DataAnalysis/3.4/NeuralNetwork/NeuralNetworkClassification.cs @ 16483

Last change on this file since 16483 was 15788, checked in by gkronber, 7 years ago

#2902 merged r15783 and r15786 from trunk to stable

File size: 12.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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 classification data analysis algorithm.
37  /// </summary>
38  [Item("Neural Network Classification (NN)", "Neural network classification data analysis algorithm (wrapper for ALGLIB). Further documentation: http://www.alglib.net/dataanalysis/neuralnetworks.php")]
39  [Creatable(CreatableAttribute.Categories.DataAnalysisClassification, Priority = 130)]
40  [StorableClass]
41  public sealed class NeuralNetworkClassification : FixedDataAnalysisAlgorithm<IClassificationProblem> {
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 NeuralNetworkClassificationModelResultName = "Neural network classification 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 NeuralNetworkClassification(bool deserializing) : base(deserializing) { }
111    private NeuralNetworkClassification(NeuralNetworkClassification original, Cloner cloner)
112      : base(original, cloner) {
113      RegisterEventHandlers();
114    }
115    public NeuralNetworkClassification()
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 ClassificationProblem();
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 NeuralNetworkClassification(this, cloner);
151    }
152    private void HiddenLayersParameterValueChanged(object source, EventArgs e) {
153      HiddenLayersParameter.Value.ValueChanged += HiddenLayersParameterValueValueChanged;
154      HiddenLayersParameterValueValueChanged(this, EventArgs.Empty);
155    }
156
157    private void HiddenLayersParameterValueValueChanged(object source, EventArgs e) {
158      if (HiddenLayers == 0) {
159        NodesInFirstHiddenLayerParameter.Hidden = true;
160        NodesInSecondHiddenLayerParameter.Hidden = true;
161      } else if (HiddenLayers == 1) {
162        NodesInFirstHiddenLayerParameter.Hidden = false;
163        NodesInSecondHiddenLayerParameter.Hidden = true;
164      } else {
165        NodesInFirstHiddenLayerParameter.Hidden = false;
166        NodesInSecondHiddenLayerParameter.Hidden = false;
167      }
168    }
169
170    #region neural network
171    protected override void Run(CancellationToken cancellationToken) {
172      double rmsError, avgRelError, relClassError;
173      var solution = CreateNeuralNetworkClassificationSolution(Problem.ProblemData, HiddenLayers, NodesInFirstHiddenLayer, NodesInSecondHiddenLayer, Decay, Restarts, out rmsError, out avgRelError, out relClassError);
174      Results.Add(new Result(NeuralNetworkClassificationModelResultName, "The neural network classification solution.", solution));
175      Results.Add(new Result("Root mean square error", "The root of the mean of squared errors of the neural network classification solution on the training set.", new DoubleValue(rmsError)));
176      Results.Add(new Result("Average relative error", "The average of relative errors of the neural network classification solution on the training set.", new PercentValue(avgRelError)));
177      Results.Add(new Result("Relative classification error", "The percentage of misclassified samples.", new PercentValue(relClassError)));
178    }
179
180    public static IClassificationSolution CreateNeuralNetworkClassificationSolution(IClassificationProblemData problemData, int nLayers, int nHiddenNodes1, int nHiddenNodes2, double decay, int restarts,
181      out double rmsError, out double avgRelError, out double relClassError) {
182      var dataset = problemData.Dataset;
183      string targetVariable = problemData.TargetVariable;
184      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
185      IEnumerable<int> rows = problemData.TrainingIndices;
186      double[,] inputMatrix = dataset.ToArray(allowedInputVariables.Concat(new string[] { targetVariable }), rows);
187      if (inputMatrix.ContainsNanOrInfinity())
188        throw new NotSupportedException("Neural network classification does not support NaN or infinity values in the input dataset.");
189
190      int nRows = inputMatrix.GetLength(0);
191      int nFeatures = inputMatrix.GetLength(1) - 1;
192      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
193      int nClasses = classValues.Count();
194      // map original class values to values [0..nClasses-1]
195      Dictionary<double, double> classIndices = new Dictionary<double, double>();
196      for (int i = 0; i < nClasses; i++) {
197        classIndices[classValues[i]] = i;
198      }
199      for (int row = 0; row < nRows; row++) {
200        inputMatrix[row, nFeatures] = classIndices[inputMatrix[row, nFeatures]];
201      }
202
203      alglib.multilayerperceptron multiLayerPerceptron = null;
204      if (nLayers == 0) {
205        alglib.mlpcreatec0(allowedInputVariables.Count(), nClasses, out multiLayerPerceptron);
206      } else if (nLayers == 1) {
207        alglib.mlpcreatec1(allowedInputVariables.Count(), nHiddenNodes1, nClasses, out multiLayerPerceptron);
208      } else if (nLayers == 2) {
209        alglib.mlpcreatec2(allowedInputVariables.Count(), nHiddenNodes1, nHiddenNodes2, nClasses, out multiLayerPerceptron);
210      } else throw new ArgumentException("Number of layers must be zero, one, or two.", "nLayers");
211      alglib.mlpreport rep;
212
213      int info;
214      // using mlptrainlm instead of mlptraines or mlptrainbfgs because only one parameter is necessary
215      alglib.mlptrainlm(multiLayerPerceptron, inputMatrix, nRows, decay, restarts, out info, out rep);
216      if (info != 2) throw new ArgumentException("Error in calculation of neural network classification solution");
217
218      rmsError = alglib.mlprmserror(multiLayerPerceptron, inputMatrix, nRows);
219      avgRelError = alglib.mlpavgrelerror(multiLayerPerceptron, inputMatrix, nRows);
220      relClassError = alglib.mlpclserror(multiLayerPerceptron, inputMatrix, nRows) / (double)nRows;
221
222      var problemDataClone = (IClassificationProblemData)problemData.Clone();
223      return new NeuralNetworkClassificationSolution(new NeuralNetworkModel(multiLayerPerceptron, targetVariable, allowedInputVariables, problemDataClone.ClassValues.ToArray()), problemDataClone);
224    }
225    #endregion
226  }
227}
Note: See TracBrowser for help on using the repository browser.