Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1720 implemented estimated class values caching in ClassificationEnsembleSolution

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