Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.DataAnalysis/3.4/NeuralNetwork/NeuralNetworkEnsembleModel.cs @ 16342

Last change on this file since 16342 was 16243, checked in by mkommend, 6 years ago

#2955: Added IsProblemDataCompatible and IsDatasetCompatible to all DataAnalysisModels.

File size: 8.9 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.Problems.DataAnalysis;
29
30namespace HeuristicLab.Algorithms.DataAnalysis {
31  /// <summary>
32  /// Represents a neural network ensembel model for regression and classification
33  /// </summary>
34  [StorableClass]
35  [Item("NeuralNetworkEnsembleModel", "Represents a neural network ensemble for regression and classification.")]
36  public sealed class NeuralNetworkEnsembleModel : ClassificationModel, INeuralNetworkEnsembleModel {
37
38    private object mlpEnsembleLocker = new object();
39    private alglib.mlpensemble mlpEnsemble;
40
41    public override IEnumerable<string> VariablesUsedForPrediction {
42      get { return allowedInputVariables; }
43    }
44
45    [Storable]
46    private string targetVariable;
47    [Storable]
48    private string[] allowedInputVariables;
49    [Storable]
50    private double[] classValues;
51    [StorableConstructor]
52    private NeuralNetworkEnsembleModel(bool deserializing)
53      : base(deserializing) {
54      if (deserializing)
55        mlpEnsemble = new alglib.mlpensemble();
56    }
57    private NeuralNetworkEnsembleModel(NeuralNetworkEnsembleModel original, Cloner cloner)
58      : base(original, cloner) {
59      mlpEnsemble = new alglib.mlpensemble();
60      string serializedEnsemble;
61      alglib.mlpeserialize(original.mlpEnsemble, out serializedEnsemble);
62      alglib.mlpeunserialize(serializedEnsemble, out this.mlpEnsemble);
63      targetVariable = original.targetVariable;
64      allowedInputVariables = (string[])original.allowedInputVariables.Clone();
65      if (original.classValues != null)
66        this.classValues = (double[])original.classValues.Clone();
67    }
68    public NeuralNetworkEnsembleModel(alglib.mlpensemble mlpEnsemble, string targetVariable, IEnumerable<string> allowedInputVariables, double[] classValues = null)
69      : base(targetVariable) {
70      this.name = ItemName;
71      this.description = ItemDescription;
72      this.mlpEnsemble = mlpEnsemble;
73      this.targetVariable = targetVariable;
74      this.allowedInputVariables = allowedInputVariables.ToArray();
75      if (classValues != null)
76        this.classValues = (double[])classValues.Clone();
77    }
78
79    public override IDeepCloneable Clone(Cloner cloner) {
80      return new NeuralNetworkEnsembleModel(this, cloner);
81    }
82
83    public IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
84      double[,] inputData = dataset.ToArray(allowedInputVariables, rows);
85
86      int n = inputData.GetLength(0);
87      int columns = inputData.GetLength(1);
88      double[] x = new double[columns];
89      double[] y = new double[1];
90
91      for (int row = 0; row < n; row++) {
92        for (int column = 0; column < columns; column++) {
93          x[column] = inputData[row, column];
94        }
95        // mlpeprocess writes data in mlpEnsemble and is therefore not thread-safe
96        lock (mlpEnsembleLocker) {
97          alglib.mlpeprocess(mlpEnsemble, x, ref y);
98        }
99        yield return y[0];
100      }
101    }
102
103    public override IEnumerable<double> GetEstimatedClassValues(IDataset dataset, IEnumerable<int> rows) {
104      double[,] inputData = dataset.ToArray(allowedInputVariables, rows);
105
106      int n = inputData.GetLength(0);
107      int columns = inputData.GetLength(1);
108      double[] x = new double[columns];
109      double[] y = new double[classValues.Length];
110
111      for (int row = 0; row < n; row++) {
112        for (int column = 0; column < columns; column++) {
113          x[column] = inputData[row, column];
114        }
115        // mlpeprocess writes data in mlpEnsemble and is therefore not thread-safe
116        lock (mlpEnsembleLocker) {
117          alglib.mlpeprocess(mlpEnsemble, x, ref y);
118        }
119        // find class for with the largest probability value
120        int maxProbClassIndex = 0;
121        double maxProb = y[0];
122        for (int i = 1; i < y.Length; i++) {
123          if (maxProb < y[i]) {
124            maxProb = y[i];
125            maxProbClassIndex = i;
126          }
127        }
128        yield return classValues[maxProbClassIndex];
129      }
130    }
131
132
133    public bool IsProblemDataCompatible(IRegressionProblemData problemData, out string errorMessage) {
134      return RegressionModel.IsProblemDataCompatible(this, problemData, out errorMessage);
135    }
136
137    public override bool IsProblemDataCompatible(IDataAnalysisProblemData problemData, out string errorMessage) {
138      if (problemData == null) throw new ArgumentNullException("problemData", "The provided problemData is null.");
139
140      var regressionProblemData = problemData as IRegressionProblemData;
141      if (regressionProblemData != null)
142        return IsProblemDataCompatible(regressionProblemData, out errorMessage);
143
144      var classificationProblemData = problemData as IClassificationProblemData;
145      if (classificationProblemData != null)
146        return IsProblemDataCompatible(classificationProblemData, out errorMessage);
147
148      throw new ArgumentException("The problem data is not a regression nor a classification problem data. Instead a " + problemData.GetType().GetPrettyName() + " was provided.", "problemData");
149    }
150
151    public IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
152      return new NeuralNetworkEnsembleRegressionSolution(this, new RegressionEnsembleProblemData(problemData));
153    }
154    public override IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
155      return new NeuralNetworkEnsembleClassificationSolution(this, new ClassificationEnsembleProblemData(problemData));
156    }
157   
158    #region persistence
159    [Storable]
160    private string MultiLayerPerceptronEnsembleNetwork {
161      get {
162        string serializedNetwork;
163        alglib.mlpeserialize(this.mlpEnsemble, out serializedNetwork);
164        return serializedNetwork;
165      }
166      set {
167        alglib.mlpeunserialize(value, out this.mlpEnsemble);
168      }
169    }
170
171    [Storable]
172    private double[] MultiLayerPerceptronEnsembleColumnMeans {
173      get { return mlpEnsemble.innerobj.columnmeans; }
174      set {
175        mlpEnsemble.innerobj.columnmeans = value;
176        mlpEnsemble.innerobj.network.columnmeans = value;
177      }
178    }
179    [Storable]
180    private double[] MultiLayerPerceptronEnsembleColumnSigmas {
181      get { return mlpEnsemble.innerobj.columnsigmas; }
182      set {
183        mlpEnsemble.innerobj.columnsigmas = value;
184        mlpEnsemble.innerobj.network.columnsigmas = value;
185      }
186    }
187    [Storable(AllowOneWay = true)]
188    private double[] MultiLayerPerceptronEnsembleDfdnet {
189      set {
190        mlpEnsemble.innerobj.network.dfdnet = value;
191      }
192    }
193    [Storable]
194    private int MultiLayerPerceptronEnsembleSize {
195      get { return mlpEnsemble.innerobj.ensemblesize; }
196      set {
197        mlpEnsemble.innerobj.ensemblesize = value;
198        mlpEnsemble.innerobj.ensemblesize = value;
199      }
200    }
201    [Storable(AllowOneWay = true)]
202    private double[] MultiLayerPerceptronEnsembleNeurons {
203      set { mlpEnsemble.innerobj.network.neurons = value; }
204    }
205    [Storable(AllowOneWay = true)]
206    private double[] MultiLayerPerceptronEnsembleSerializedMlp {
207      set {
208        mlpEnsemble.innerobj.network.dfdnet = value;
209      }
210    }
211    [Storable(AllowOneWay = true)]
212    private int[] MultiLayerPerceptronStuctinfo {
213      set {
214        mlpEnsemble.innerobj.network.structinfo = value;
215      }
216    }
217
218    [Storable]
219    private double[] MultiLayerPerceptronWeights {
220      get {
221        return mlpEnsemble.innerobj.weights;
222      }
223      set {
224        mlpEnsemble.innerobj.weights = value;
225        mlpEnsemble.innerobj.network.weights = value;
226      }
227    }
228    [Storable]
229    private double[] MultiLayerPerceptronY {
230      get {
231        return mlpEnsemble.innerobj.y;
232      }
233      set {
234        mlpEnsemble.innerobj.y = value;
235        mlpEnsemble.innerobj.network.y = value;
236      }
237    }
238    #endregion
239  }
240}
Note: See TracBrowser for help on using the repository browser.