Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationEnsembleSolution.cs @ 8364

Last change on this file since 8364 was 8174, checked in by sforsten, 12 years ago

#1720: added some small memory allocation improvements. The caches are initialized with the correct size, so no reallocation for the caches is necessary.

File size: 15.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Problems.DataAnalysis {
32  /// <summary>
33  /// Represents classification solutions that contain an ensemble of multiple classification models
34  /// </summary>
35  [StorableClass]
36  [Item("Classification Ensemble Solution", "A classification solution that contains an ensemble of multiple classification models")]
37  [Creatable("Data Analysis - Ensembles")]
38  public sealed class ClassificationEnsembleSolution : ClassificationSolution, IClassificationEnsembleSolution {
39    private readonly Dictionary<int, double> trainingEvaluationCache = new Dictionary<int, double>();
40    private readonly Dictionary<int, double> testEvaluationCache = new Dictionary<int, double>();
41
42    public new IClassificationEnsembleModel Model {
43      get { return (IClassificationEnsembleModel)base.Model; }
44    }
45    public new ClassificationEnsembleProblemData ProblemData {
46      get { return (ClassificationEnsembleProblemData)base.ProblemData; }
47      set { base.ProblemData = value; }
48    }
49
50    private readonly ItemCollection<IClassificationSolution> classificationSolutions;
51    public IItemCollection<IClassificationSolution> ClassificationSolutions {
52      get { return classificationSolutions; }
53    }
54
55    [Storable]
56    private Dictionary<IClassificationModel, IntRange> trainingPartitions;
57    [Storable]
58    private Dictionary<IClassificationModel, IntRange> testPartitions;
59
60    [StorableConstructor]
61    private ClassificationEnsembleSolution(bool deserializing)
62      : base(deserializing) {
63      classificationSolutions = new ItemCollection<IClassificationSolution>();
64    }
65    [StorableHook(HookType.AfterDeserialization)]
66    private void AfterDeserialization() {
67      foreach (var model in Model.Models) {
68        IClassificationProblemData problemData = (IClassificationProblemData)ProblemData.Clone();
69        problemData.TrainingPartition.Start = trainingPartitions[model].Start;
70        problemData.TrainingPartition.End = trainingPartitions[model].End;
71        problemData.TestPartition.Start = testPartitions[model].Start;
72        problemData.TestPartition.End = testPartitions[model].End;
73
74        classificationSolutions.Add(model.CreateClassificationSolution(problemData));
75      }
76      RegisterClassificationSolutionsEventHandler();
77    }
78
79    private ClassificationEnsembleSolution(ClassificationEnsembleSolution original, Cloner cloner)
80      : base(original, cloner) {
81      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
82      testPartitions = new Dictionary<IClassificationModel, IntRange>();
83      foreach (var pair in original.trainingPartitions) {
84        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
85      }
86      foreach (var pair in original.testPartitions) {
87        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
88      }
89
90      trainingEvaluationCache = new Dictionary<int, double>(original.ProblemData.TrainingIndices.Count());
91      testEvaluationCache = new Dictionary<int, double>(original.ProblemData.TestIndices.Count());
92
93      classificationSolutions = cloner.Clone(original.classificationSolutions);
94      RegisterClassificationSolutionsEventHandler();
95    }
96
97    public ClassificationEnsembleSolution()
98      : base(new ClassificationEnsembleModel(), ClassificationEnsembleProblemData.EmptyProblemData) {
99      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
100      testPartitions = new Dictionary<IClassificationModel, IntRange>();
101      classificationSolutions = new ItemCollection<IClassificationSolution>();
102
103      RegisterClassificationSolutionsEventHandler();
104    }
105
106    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData)
107      : this(models, problemData,
108             models.Select(m => (IntRange)problemData.TrainingPartition.Clone()),
109             models.Select(m => (IntRange)problemData.TestPartition.Clone())
110      ) { }
111
112    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions)
113      : base(new ClassificationEnsembleModel(Enumerable.Empty<IClassificationModel>()), new ClassificationEnsembleProblemData(problemData)) {
114      this.trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
115      this.testPartitions = new Dictionary<IClassificationModel, IntRange>();
116      this.classificationSolutions = new ItemCollection<IClassificationSolution>();
117
118      List<IClassificationSolution> solutions = new List<IClassificationSolution>();
119      var modelEnumerator = models.GetEnumerator();
120      var trainingPartitionEnumerator = trainingPartitions.GetEnumerator();
121      var testPartitionEnumerator = testPartitions.GetEnumerator();
122
123      while (modelEnumerator.MoveNext() & trainingPartitionEnumerator.MoveNext() & testPartitionEnumerator.MoveNext()) {
124        var p = (IClassificationProblemData)problemData.Clone();
125        p.TrainingPartition.Start = trainingPartitionEnumerator.Current.Start;
126        p.TrainingPartition.End = trainingPartitionEnumerator.Current.End;
127        p.TestPartition.Start = testPartitionEnumerator.Current.Start;
128        p.TestPartition.End = testPartitionEnumerator.Current.End;
129
130        solutions.Add(modelEnumerator.Current.CreateClassificationSolution(p));
131      }
132      if (modelEnumerator.MoveNext() | trainingPartitionEnumerator.MoveNext() | testPartitionEnumerator.MoveNext()) {
133        throw new ArgumentException();
134      }
135
136      trainingEvaluationCache = new Dictionary<int, double>(problemData.TrainingIndices.Count());
137      testEvaluationCache = new Dictionary<int, double>(problemData.TestIndices.Count());
138
139      RegisterClassificationSolutionsEventHandler();
140      classificationSolutions.AddRange(solutions);
141    }
142
143    public override IDeepCloneable Clone(Cloner cloner) {
144      return new ClassificationEnsembleSolution(this, cloner);
145    }
146    private void RegisterClassificationSolutionsEventHandler() {
147      classificationSolutions.ItemsAdded += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_ItemsAdded);
148      classificationSolutions.ItemsRemoved += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_ItemsRemoved);
149      classificationSolutions.CollectionReset += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_CollectionReset);
150    }
151
152    protected override void RecalculateResults() {
153      CalculateResults();
154    }
155
156    #region Evaluation
157    public override IEnumerable<double> EstimatedTrainingClassValues {
158      get {
159        var rows = ProblemData.TrainingIndices;
160        var rowsToEvaluate = rows.Except(trainingEvaluationCache.Keys);
161        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
162        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, (r, m) => RowIsTrainingForModel(r, m) && !RowIsTestForModel(r, m)).GetEnumerator();
163
164        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
165          trainingEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
166        }
167
168        return rows.Select(row => trainingEvaluationCache[row]);
169      }
170    }
171
172    public override IEnumerable<double> EstimatedTestClassValues {
173      get {
174        var rows = ProblemData.TestIndices;
175        var rowsToEvaluate = rows.Except(testEvaluationCache.Keys);
176        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
177        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, RowIsTestForModel).GetEnumerator();
178
179        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
180          testEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
181        }
182
183        return rows.Select(row => testEvaluationCache[row]);
184      }
185    }
186
187    private IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows, Func<int, IClassificationModel, bool> modelSelectionPredicate) {
188      var estimatedValuesEnumerators = (from model in Model.Models
189                                        select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
190                                       .ToList();
191      var rowsEnumerator = rows.GetEnumerator();
192      // aggregate to make sure that MoveNext is called for all enumerators
193      while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
194        int currentRow = rowsEnumerator.Current;
195
196        var selectedEnumerators = from pair in estimatedValuesEnumerators
197                                  where modelSelectionPredicate(currentRow, pair.Model)
198                                  select pair.EstimatedValuesEnumerator;
199
200        yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
201      }
202    }
203
204    private bool RowIsTrainingForModel(int currentRow, IClassificationModel model) {
205      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
206              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
207    }
208
209    private bool RowIsTestForModel(int currentRow, IClassificationModel model) {
210      return testPartitions == null || !testPartitions.ContainsKey(model) ||
211              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
212    }
213
214    public override IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows) {
215      var rowsToEvaluate = rows.Except(evaluationCache.Keys);
216      var rowsEnumerator = rowsToEvaluate.GetEnumerator();
217      var valuesEnumerator = (from xs in GetEstimatedClassValueVectors(ProblemData.Dataset, rowsToEvaluate)
218                              select AggregateEstimatedClassValues(xs))
219                             .GetEnumerator();
220
221      while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
222        evaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
223      }
224
225      return rows.Select(row => evaluationCache[row]);
226    }
227
228    public IEnumerable<IEnumerable<double>> GetEstimatedClassValueVectors(Dataset dataset, IEnumerable<int> rows) {
229      if (!Model.Models.Any()) yield break;
230      var estimatedValuesEnumerators = (from model in Model.Models
231                                        select model.GetEstimatedClassValues(dataset, rows).GetEnumerator())
232                                       .ToList();
233
234      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
235        yield return from enumerator in estimatedValuesEnumerators
236                     select enumerator.Current;
237      }
238    }
239
240    private double AggregateEstimatedClassValues(IEnumerable<double> estimatedClassValues) {
241      return estimatedClassValues
242      .GroupBy(x => x)
243      .OrderBy(g => -g.Count())
244      .Select(g => g.Key)
245      .DefaultIfEmpty(double.NaN)
246      .First();
247    }
248    #endregion
249
250    protected override void OnProblemDataChanged() {
251      trainingEvaluationCache.Clear();
252      testEvaluationCache.Clear();
253      evaluationCache.Clear();
254
255      IClassificationProblemData problemData = new ClassificationProblemData(ProblemData.Dataset,
256                                                                     ProblemData.AllowedInputVariables,
257                                                                     ProblemData.TargetVariable);
258      problemData.TrainingPartition.Start = ProblemData.TrainingPartition.Start;
259      problemData.TrainingPartition.End = ProblemData.TrainingPartition.End;
260      problemData.TestPartition.Start = ProblemData.TestPartition.Start;
261      problemData.TestPartition.End = ProblemData.TestPartition.End;
262
263      foreach (var solution in ClassificationSolutions) {
264        if (solution is ClassificationEnsembleSolution)
265          solution.ProblemData = ProblemData;
266        else
267          solution.ProblemData = problemData;
268      }
269      foreach (var trainingPartition in trainingPartitions.Values) {
270        trainingPartition.Start = ProblemData.TrainingPartition.Start;
271        trainingPartition.End = ProblemData.TrainingPartition.End;
272      }
273      foreach (var testPartition in testPartitions.Values) {
274        testPartition.Start = ProblemData.TestPartition.Start;
275        testPartition.End = ProblemData.TestPartition.End;
276      }
277
278      base.OnProblemDataChanged();
279    }
280
281    public void AddClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
282      classificationSolutions.AddRange(solutions);
283
284      trainingEvaluationCache.Clear();
285      testEvaluationCache.Clear();
286      evaluationCache.Clear();
287    }
288    public void RemoveClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
289      classificationSolutions.RemoveRange(solutions);
290
291      trainingEvaluationCache.Clear();
292      testEvaluationCache.Clear();
293      evaluationCache.Clear();
294    }
295
296    private void classificationSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
297      foreach (var solution in e.Items) AddClassificationSolution(solution);
298      RecalculateResults();
299    }
300    private void classificationSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
301      foreach (var solution in e.Items) RemoveClassificationSolution(solution);
302      RecalculateResults();
303    }
304    private void classificationSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
305      foreach (var solution in e.OldItems) RemoveClassificationSolution(solution);
306      foreach (var solution in e.Items) AddClassificationSolution(solution);
307      RecalculateResults();
308    }
309
310    private void AddClassificationSolution(IClassificationSolution solution) {
311      if (Model.Models.Contains(solution.Model)) throw new ArgumentException();
312      Model.Add(solution.Model);
313      trainingPartitions[solution.Model] = solution.ProblemData.TrainingPartition;
314      testPartitions[solution.Model] = solution.ProblemData.TestPartition;
315
316      trainingEvaluationCache.Clear();
317      testEvaluationCache.Clear();
318      evaluationCache.Clear();
319    }
320
321    private void RemoveClassificationSolution(IClassificationSolution solution) {
322      if (!Model.Models.Contains(solution.Model)) throw new ArgumentException();
323      Model.Remove(solution.Model);
324      trainingPartitions.Remove(solution.Model);
325      testPartitions.Remove(solution.Model);
326
327      trainingEvaluationCache.Clear();
328      testEvaluationCache.Clear();
329      evaluationCache.Clear();
330    }
331  }
332}
Note: See TracBrowser for help on using the repository browser.