Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6613 was 6613, checked in by mkommend, 13 years ago

#1592: Implemented view for classification solutions contained in a ClassificationEnsembleSolution.

File size: 12.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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")]
38  public sealed class ClassificationEnsembleSolution : ClassificationSolution, IClassificationEnsembleSolution {
39    public new IClassificationEnsembleModel Model {
40      get { return (IClassificationEnsembleModel)base.Model; }
41    }
42
43    private readonly ItemCollection<IClassificationSolution> classificationSolutions;
44    public IItemCollection<IClassificationSolution> ClassificationSolutions {
45      get { return classificationSolutions; }
46    }
47
48    [Storable]
49    private Dictionary<IClassificationModel, IntRange> trainingPartitions;
50    [Storable]
51    private Dictionary<IClassificationModel, IntRange> testPartitions;
52
53    [StorableConstructor]
54    private ClassificationEnsembleSolution(bool deserializing)
55      : base(deserializing) {
56      classificationSolutions = new ItemCollection<IClassificationSolution>();
57    }
58    [StorableHook(HookType.AfterDeserialization)]
59    private void AfterDeserialization() {
60      foreach (var model in Model.Models) {
61        IClassificationProblemData problemData = (IClassificationProblemData)ProblemData.Clone();
62        problemData.TrainingPartition.Start = trainingPartitions[model].Start;
63        problemData.TrainingPartition.End = trainingPartitions[model].End;
64        problemData.TestPartition.Start = testPartitions[model].Start;
65        problemData.TestPartition.End = testPartitions[model].End;
66
67        classificationSolutions.Add(model.CreateClassificationSolution(problemData));
68      }
69      RegisterClassificationSolutionsEventHandler();
70    }
71
72    private ClassificationEnsembleSolution(ClassificationEnsembleSolution original, Cloner cloner)
73      : base(original, cloner) {
74      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
75      testPartitions = new Dictionary<IClassificationModel, IntRange>();
76      foreach (var pair in original.trainingPartitions) {
77        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
78      }
79      foreach (var pair in original.testPartitions) {
80        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
81      }
82
83      classificationSolutions = cloner.Clone(original.classificationSolutions);
84      RegisterClassificationSolutionsEventHandler();
85    }
86
87    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData)
88      : this(models, problemData,
89             models.Select(m => (IntRange)problemData.TrainingPartition.Clone()),
90             models.Select(m => (IntRange)problemData.TestPartition.Clone())
91      ) { }
92
93    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions)
94      : base(new ClassificationEnsembleModel(Enumerable.Empty<IClassificationModel>()), new ClassificationEnsembleProblemData(problemData)) {
95      this.trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
96      this.testPartitions = new Dictionary<IClassificationModel, IntRange>();
97      this.classificationSolutions = new ItemCollection<IClassificationSolution>();
98
99      List<IClassificationSolution> solutions = new List<IClassificationSolution>();
100      var modelEnumerator = models.GetEnumerator();
101      var trainingPartitionEnumerator = trainingPartitions.GetEnumerator();
102      var testPartitionEnumerator = testPartitions.GetEnumerator();
103
104      while (modelEnumerator.MoveNext() & trainingPartitionEnumerator.MoveNext() & testPartitionEnumerator.MoveNext()) {
105        var p = (IClassificationProblemData)problemData.Clone();
106        p.TrainingPartition.Start = trainingPartitionEnumerator.Current.Start;
107        p.TrainingPartition.End = trainingPartitionEnumerator.Current.End;
108        p.TestPartition.Start = testPartitionEnumerator.Current.Start;
109        p.TestPartition.End = testPartitionEnumerator.Current.End;
110
111        solutions.Add(modelEnumerator.Current.CreateClassificationSolution(p));
112      }
113      if (modelEnumerator.MoveNext() | trainingPartitionEnumerator.MoveNext() | testPartitionEnumerator.MoveNext()) {
114        throw new ArgumentException();
115      }
116
117      RegisterClassificationSolutionsEventHandler();
118      classificationSolutions.AddRange(solutions);
119    }
120
121    public override IDeepCloneable Clone(Cloner cloner) {
122      return new ClassificationEnsembleSolution(this, cloner);
123    }
124    private void RegisterClassificationSolutionsEventHandler() {
125      classificationSolutions.ItemsAdded += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_ItemsAdded);
126      classificationSolutions.ItemsRemoved += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_ItemsRemoved);
127      classificationSolutions.CollectionReset += new CollectionItemsChangedEventHandler<IClassificationSolution>(classificationSolutions_CollectionReset);
128    }
129
130    protected override void RecalculateResults() {
131      CalculateResults();
132    }
133
134    #region Evaluation
135    public override IEnumerable<double> EstimatedTrainingClassValues {
136      get {
137        var rows = ProblemData.TrainingIndizes;
138        var estimatedValuesEnumerators = (from model in Model.Models
139                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
140                                         .ToList();
141        var rowsEnumerator = rows.GetEnumerator();
142        // aggregate to make sure that MoveNext is called for all enumerators
143        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
144          int currentRow = rowsEnumerator.Current;
145
146          var selectedEnumerators = from pair in estimatedValuesEnumerators
147                                    where RowIsTrainingForModel(currentRow, pair.Model) && !RowIsTestForModel(currentRow, pair.Model)
148                                    select pair.EstimatedValuesEnumerator;
149          yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
150        }
151      }
152    }
153
154    public override IEnumerable<double> EstimatedTestClassValues {
155      get {
156        var rows = ProblemData.TestIndizes;
157        var estimatedValuesEnumerators = (from model in Model.Models
158                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
159                                         .ToList();
160        var rowsEnumerator = ProblemData.TestIndizes.GetEnumerator();
161        // aggregate to make sure that MoveNext is called for all enumerators
162        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
163          int currentRow = rowsEnumerator.Current;
164
165          var selectedEnumerators = from pair in estimatedValuesEnumerators
166                                    where RowIsTestForModel(currentRow, pair.Model)
167                                    select pair.EstimatedValuesEnumerator;
168
169          yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
170        }
171      }
172    }
173
174    private bool RowIsTrainingForModel(int currentRow, IClassificationModel model) {
175      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
176              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
177    }
178
179    private bool RowIsTestForModel(int currentRow, IClassificationModel model) {
180      return testPartitions == null || !testPartitions.ContainsKey(model) ||
181              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
182    }
183
184    public override IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows) {
185      return from xs in GetEstimatedClassValueVectors(ProblemData.Dataset, rows)
186             select AggregateEstimatedClassValues(xs);
187    }
188
189    public IEnumerable<IEnumerable<double>> GetEstimatedClassValueVectors(Dataset dataset, IEnumerable<int> rows) {
190      var estimatedValuesEnumerators = (from model in Model.Models
191                                        select model.GetEstimatedClassValues(dataset, rows).GetEnumerator())
192                                       .ToList();
193
194      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
195        yield return from enumerator in estimatedValuesEnumerators
196                     select enumerator.Current;
197      }
198    }
199
200    private double AggregateEstimatedClassValues(IEnumerable<double> estimatedClassValues) {
201      return estimatedClassValues
202      .GroupBy(x => x)
203      .OrderBy(g => -g.Count())
204      .Select(g => g.Key)
205      .DefaultIfEmpty(double.NaN)
206      .First();
207    }
208    #endregion
209
210    public void AddClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
211      classificationSolutions.AddRange(solutions);
212    }
213    public void RemoveClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
214      classificationSolutions.RemoveRange(solutions);
215    }
216
217    private void classificationSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
218      foreach (var solution in e.Items) AddClassificationSolution(solution);
219      RecalculateResults();
220    }
221    private void classificationSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
222      foreach (var solution in e.Items) RemoveClassificationSolution(solution);
223      RecalculateResults();
224    }
225    private void classificationSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
226      foreach (var solution in e.OldItems) RemoveClassificationSolution(solution);
227      foreach (var solution in e.Items) AddClassificationSolution(solution);
228      RecalculateResults();
229    }
230
231    private void AddClassificationSolution(IClassificationSolution solution) {
232      if (Model.Models.Contains(solution.Model)) throw new ArgumentException();
233      Model.Add(solution.Model);
234      trainingPartitions[solution.Model] = solution.ProblemData.TrainingPartition;
235      testPartitions[solution.Model] = solution.ProblemData.TestPartition;
236    }
237
238    private void RemoveClassificationSolution(IClassificationSolution solution) {
239      if (!Model.Models.Contains(solution.Model)) throw new ArgumentException();
240      Model.Remove(solution.Model);
241      trainingPartitions.Remove(solution.Model);
242      testPartitions.Remove(solution.Model);
243    }
244  }
245}
Note: See TracBrowser for help on using the repository browser.