Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3027-NormalDistribution/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationEnsembleSolution.cs @ 17399

Last change on this file since 17399 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

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