Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HLScript/HeuristicLab.Algorithms.DataAnalysis/3.4/NeuralNetwork/NeuralNetworkClassification.cs @ 12406

Last change on this file since 12406 was 9919, checked in by gkronber, 11 years ago

#2101: fixed strings in classes for ANNs

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