Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2902 merged r15783 and r15786 from trunk to stable

File size: 12.2 KB
RevLine 
[6577]1#region License Information
2/* HeuristicLab
[15584]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6577]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;
[15061]25using System.Threading;
[6577]26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Optimization;
[10030]30using HeuristicLab.Parameters;
[6577]31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33
34namespace HeuristicLab.Algorithms.DataAnalysis {
35  /// <summary>
[6579]36  /// Neural network classification data analysis algorithm.
[6577]37  /// </summary>
[13297]38  [Item("Neural Network Classification (NN)", "Neural network classification data analysis algorithm (wrapper for ALGLIB). Further documentation: http://www.alglib.net/dataanalysis/neuralnetworks.php")]
[12708]39  [Creatable(CreatableAttribute.Categories.DataAnalysisClassification, Priority = 130)]
[6577]40  [StorableClass]
[6579]41  public sealed class NeuralNetworkClassification : FixedDataAnalysisAlgorithm<IClassificationProblem> {
[6578]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";
[10030]47    private const string NeuralNetworkClassificationModelResultName = "Neural network classification solution";
[6578]48
49    #region parameter properties
50    public IFixedValueParameter<DoubleValue> DecayParameter {
51      get { return (IFixedValueParameter<DoubleValue>)Parameters[DecayParameterName]; }
52    }
[8121]53    public IConstrainedValueParameter<IntValue> HiddenLayersParameter {
54      get { return (IConstrainedValueParameter<IntValue>)Parameters[HiddenLayersParameterName]; }
[6578]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
[6577]109    [StorableConstructor]
[6579]110    private NeuralNetworkClassification(bool deserializing) : base(deserializing) { }
111    private NeuralNetworkClassification(NeuralNetworkClassification original, Cloner cloner)
[6577]112      : base(original, cloner) {
[6720]113      RegisterEventHandlers();
[6577]114    }
[6579]115    public NeuralNetworkClassification()
[6577]116      : base() {
[15788]117      var validHiddenLayerValues = new ItemSet<IntValue>(new IntValue[] {
118        (IntValue)new IntValue(0).AsReadOnly(),
119        (IntValue)new IntValue(1).AsReadOnly(),
[6720]120        (IntValue)new IntValue(2).AsReadOnly() });
[6578]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
[6720]131      RestartsParameter.Hidden = true;
132      NodesInSecondHiddenLayerParameter.Hidden = true;
133
134      RegisterEventHandlers();
135
[6579]136      Problem = new ClassificationProblem();
[6577]137    }
[6720]138
139    private void RegisterEventHandlers() {
140      HiddenLayersParameter.Value.ValueChanged += HiddenLayersParameterValueValueChanged;
141      HiddenLayersParameter.ValueChanged += HiddenLayersParameterValueChanged;
142    }
143
[6577]144    [StorableHook(HookType.AfterDeserialization)]
[6720]145    private void AfterDeserialization() {
146      RegisterEventHandlers();
147    }
[6577]148
149    public override IDeepCloneable Clone(Cloner cloner) {
[6579]150      return new NeuralNetworkClassification(this, cloner);
[6577]151    }
[6720]152    private void HiddenLayersParameterValueChanged(object source, EventArgs e) {
153      HiddenLayersParameter.Value.ValueChanged += HiddenLayersParameterValueValueChanged;
154      HiddenLayersParameterValueValueChanged(this, EventArgs.Empty);
155    }
[6577]156
[6720]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
[6577]170    #region neural network
[15061]171    protected override void Run(CancellationToken cancellationToken) {
[6579]172      double rmsError, avgRelError, relClassError;
173      var solution = CreateNeuralNetworkClassificationSolution(Problem.ProblemData, HiddenLayers, NodesInFirstHiddenLayer, NodesInSecondHiddenLayer, Decay, Restarts, out rmsError, out avgRelError, out relClassError);
[10030]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)));
[6579]177      Results.Add(new Result("Relative classification error", "The percentage of misclassified samples.", new PercentValue(relClassError)));
[6577]178    }
179
[6579]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) {
[12702]182      var dataset = problemData.Dataset;
[6577]183      string targetVariable = problemData.TargetVariable;
184      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
[8139]185      IEnumerable<int> rows = problemData.TrainingIndices;
[15142]186      double[,] inputMatrix = dataset.ToArray(allowedInputVariables.Concat(new string[] { targetVariable }), rows);
[15788]187      if (inputMatrix.ContainsNanOrInfinity())
[6579]188        throw new NotSupportedException("Neural network classification does not support NaN or infinity values in the input dataset.");
[6577]189
190      int nRows = inputMatrix.GetLength(0);
[6579]191      int nFeatures = inputMatrix.GetLength(1) - 1;
[6740]192      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
[6579]193      int nClasses = classValues.Count();
194      // map original class values to values [0..nClasses-1]
[8139]195      Dictionary<double, double> classIndices = new Dictionary<double, double>();
[6579]196      for (int i = 0; i < nClasses; i++) {
[8139]197        classIndices[classValues[i]] = i;
[6579]198      }
199      for (int row = 0; row < nRows; row++) {
[8139]200        inputMatrix[row, nFeatures] = classIndices[inputMatrix[row, nFeatures]];
[6579]201      }
[6577]202
[6580]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
[6577]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);
[6579]216      if (info != 2) throw new ArgumentException("Error in calculation of neural network classification solution");
[6577]217
218      rmsError = alglib.mlprmserror(multiLayerPerceptron, inputMatrix, nRows);
[6578]219      avgRelError = alglib.mlpavgrelerror(multiLayerPerceptron, inputMatrix, nRows);
[6579]220      relClassError = alglib.mlpclserror(multiLayerPerceptron, inputMatrix, nRows) / (double)nRows;
[6577]221
[6649]222      var problemDataClone = (IClassificationProblemData)problemData.Clone();
[14027]223      return new NeuralNetworkClassificationSolution(new NeuralNetworkModel(multiLayerPerceptron, targetVariable, allowedInputVariables, problemDataClone.ClassValues.ToArray()), problemDataClone);
[6577]224    }
225    #endregion
226  }
227}
Note: See TracBrowser for help on using the repository browser.