Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8167 was 8167, checked in by gkronber, 12 years ago

#1720 reused evaluationCache from base classes in EnsembleSolutions

File size: 15.4 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      classificationSolutions = cloner.Clone(original.classificationSolutions);
91      RegisterClassificationSolutionsEventHandler();
92    }
93
94    public ClassificationEnsembleSolution()
95      : base(new ClassificationEnsembleModel(), ClassificationEnsembleProblemData.EmptyProblemData) {
96      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
97      testPartitions = new Dictionary<IClassificationModel, IntRange>();
98      classificationSolutions = new ItemCollection<IClassificationSolution>();
99
100      RegisterClassificationSolutionsEventHandler();
101    }
102
103    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData)
104      : this(models, problemData,
105             models.Select(m => (IntRange)problemData.TrainingPartition.Clone()),
106             models.Select(m => (IntRange)problemData.TestPartition.Clone())
107      ) { }
108
109    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions)
110      : base(new ClassificationEnsembleModel(Enumerable.Empty<IClassificationModel>()), new ClassificationEnsembleProblemData(problemData)) {
111      this.trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
112      this.testPartitions = new Dictionary<IClassificationModel, IntRange>();
113      this.classificationSolutions = new ItemCollection<IClassificationSolution>();
114
115      List<IClassificationSolution> solutions = new List<IClassificationSolution>();
116      var modelEnumerator = models.GetEnumerator();
117      var trainingPartitionEnumerator = trainingPartitions.GetEnumerator();
118      var testPartitionEnumerator = testPartitions.GetEnumerator();
119
120      while (modelEnumerator.MoveNext() & trainingPartitionEnumerator.MoveNext() & testPartitionEnumerator.MoveNext()) {
121        var p = (IClassificationProblemData)problemData.Clone();
122        p.TrainingPartition.Start = trainingPartitionEnumerator.Current.Start;
123        p.TrainingPartition.End = trainingPartitionEnumerator.Current.End;
124        p.TestPartition.Start = testPartitionEnumerator.Current.Start;
125        p.TestPartition.End = testPartitionEnumerator.Current.End;
126
127        solutions.Add(modelEnumerator.Current.CreateClassificationSolution(p));
128      }
129      if (modelEnumerator.MoveNext() | trainingPartitionEnumerator.MoveNext() | testPartitionEnumerator.MoveNext()) {
130        throw new ArgumentException();
131      }
132
133      RegisterClassificationSolutionsEventHandler();
134      classificationSolutions.AddRange(solutions);
135    }
136
137    public override IDeepCloneable Clone(Cloner cloner) {
138      return new ClassificationEnsembleSolution(this, cloner);
139    }
140    private void RegisterClassificationSolutionsEventHandler() {
141      classificationSolutions.ItemsAdded += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_ItemsAdded);
142      classificationSolutions.ItemsRemoved += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_ItemsRemoved);
143      classificationSolutions.CollectionReset += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_CollectionReset);
144    }
145
146    protected override void RecalculateResults() {
147      CalculateResults();
148    }
149
150    #region Evaluation
151    public override IEnumerable<double> EstimatedTrainingClassValues {
152      get {
153        var rows = ProblemData.TrainingIndices;
154        var rowsToEvaluate = rows.Except(trainingEvaluationCache.Keys);
155        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
156        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, (r, m) => RowIsTrainingForModel(r, m) && !RowIsTestForModel(r, m)).GetEnumerator();
157
158        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
159          trainingEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
160        }
161
162        return rows.Select(row => trainingEvaluationCache[row]);
163      }
164    }
165
166    public override IEnumerable<double> EstimatedTestClassValues {
167      get {
168        var rows = ProblemData.TestIndices;
169        var rowsToEvaluate = rows.Except(testEvaluationCache.Keys);
170        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
171        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, RowIsTestForModel).GetEnumerator();
172
173        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
174          testEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
175        }
176
177        return rows.Select(row => testEvaluationCache[row]);
178      }
179    }
180
181    private IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows, Func<int, IClassificationModel, bool> modelSelectionPredicate) {
182      var estimatedValuesEnumerators = (from model in Model.Models
183                                        select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
184                                       .ToList();
185      var rowsEnumerator = rows.GetEnumerator();
186      // aggregate to make sure that MoveNext is called for all enumerators
187      while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
188        int currentRow = rowsEnumerator.Current;
189
190        var selectedEnumerators = from pair in estimatedValuesEnumerators
191                                  where modelSelectionPredicate(currentRow, pair.Model)
192                                  select pair.EstimatedValuesEnumerator;
193
194        yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
195      }
196    }
197
198    private bool RowIsTrainingForModel(int currentRow, IClassificationModel model) {
199      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
200              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
201    }
202
203    private bool RowIsTestForModel(int currentRow, IClassificationModel model) {
204      return testPartitions == null || !testPartitions.ContainsKey(model) ||
205              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
206    }
207
208    public override IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows) {
209      var rowsToEvaluate = rows.Except(evaluationCache.Keys);
210      var rowsEnumerator = rowsToEvaluate.GetEnumerator();
211      var valuesEnumerator = (from xs in GetEstimatedClassValueVectors(ProblemData.Dataset, rowsToEvaluate)
212                              select AggregateEstimatedClassValues(xs))
213                             .GetEnumerator();
214
215      while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
216        evaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
217      }
218
219      return rows.Select(row => evaluationCache[row]);
220    }
221
222    public IEnumerable<IEnumerable<double>> GetEstimatedClassValueVectors(Dataset dataset, IEnumerable<int> rows) {
223      if (!Model.Models.Any()) yield break;
224      var estimatedValuesEnumerators = (from model in Model.Models
225                                        select model.GetEstimatedClassValues(dataset, rows).GetEnumerator())
226                                       .ToList();
227
228      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
229        yield return from enumerator in estimatedValuesEnumerators
230                     select enumerator.Current;
231      }
232    }
233
234    private double AggregateEstimatedClassValues(IEnumerable<double> estimatedClassValues) {
235      return estimatedClassValues
236      .GroupBy(x => x)
237      .OrderBy(g => -g.Count())
238      .Select(g => g.Key)
239      .DefaultIfEmpty(double.NaN)
240      .First();
241    }
242    #endregion
243
244    protected override void OnProblemDataChanged() {
245      trainingEvaluationCache.Clear();
246      testEvaluationCache.Clear();
247      evaluationCache.Clear();
248
249      IClassificationProblemData problemData = new ClassificationProblemData(ProblemData.Dataset,
250                                                                     ProblemData.AllowedInputVariables,
251                                                                     ProblemData.TargetVariable);
252      problemData.TrainingPartition.Start = ProblemData.TrainingPartition.Start;
253      problemData.TrainingPartition.End = ProblemData.TrainingPartition.End;
254      problemData.TestPartition.Start = ProblemData.TestPartition.Start;
255      problemData.TestPartition.End = ProblemData.TestPartition.End;
256
257      foreach (var solution in ClassificationSolutions) {
258        if (solution is ClassificationEnsembleSolution)
259          solution.ProblemData = ProblemData;
260        else
261          solution.ProblemData = problemData;
262      }
263      foreach (var trainingPartition in trainingPartitions.Values) {
264        trainingPartition.Start = ProblemData.TrainingPartition.Start;
265        trainingPartition.End = ProblemData.TrainingPartition.End;
266      }
267      foreach (var testPartition in testPartitions.Values) {
268        testPartition.Start = ProblemData.TestPartition.Start;
269        testPartition.End = ProblemData.TestPartition.End;
270      }
271
272      base.OnProblemDataChanged();
273    }
274
275    public void AddClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
276      classificationSolutions.AddRange(solutions);
277
278      trainingEvaluationCache.Clear();
279      testEvaluationCache.Clear();
280      evaluationCache.Clear();
281    }
282    public void RemoveClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
283      classificationSolutions.RemoveRange(solutions);
284
285      trainingEvaluationCache.Clear();
286      testEvaluationCache.Clear();
287      evaluationCache.Clear();
288    }
289
290    private void classificationSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
291      foreach (var solution in e.Items) AddClassificationSolution(solution);
292      RecalculateResults();
293    }
294    private void classificationSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
295      foreach (var solution in e.Items) RemoveClassificationSolution(solution);
296      RecalculateResults();
297    }
298    private void classificationSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
299      foreach (var solution in e.OldItems) RemoveClassificationSolution(solution);
300      foreach (var solution in e.Items) AddClassificationSolution(solution);
301      RecalculateResults();
302    }
303
304    private void AddClassificationSolution(IClassificationSolution solution) {
305      if (Model.Models.Contains(solution.Model)) throw new ArgumentException();
306      Model.Add(solution.Model);
307      trainingPartitions[solution.Model] = solution.ProblemData.TrainingPartition;
308      testPartitions[solution.Model] = solution.ProblemData.TestPartition;
309
310      trainingEvaluationCache.Clear();
311      testEvaluationCache.Clear();
312      evaluationCache.Clear();
313    }
314
315    private void RemoveClassificationSolution(IClassificationSolution solution) {
316      if (!Model.Models.Contains(solution.Model)) throw new ArgumentException();
317      Model.Remove(solution.Model);
318      trainingPartitions.Remove(solution.Model);
319      testPartitions.Remove(solution.Model);
320
321      trainingEvaluationCache.Clear();
322      testEvaluationCache.Clear();
323      evaluationCache.Clear();
324    }
325  }
326}
Note: See TracBrowser for help on using the repository browser.