Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationEnsembleSolution.cs @ 18131

Last change on this file since 18131 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

File size: 16.2 KB
RevLine 
[5816]1#region License Information
2/* HeuristicLab
[17181]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5816]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
[6589]22using System;
[5816]23using System.Collections.Generic;
24using System.Linq;
[6613]25using HeuristicLab.Collections;
[5816]26using HeuristicLab.Common;
27using HeuristicLab.Core;
[6589]28using HeuristicLab.Data;
[17097]29using HEAL.Attic;
[5816]30
31namespace HeuristicLab.Problems.DataAnalysis {
32  /// <summary>
33  /// Represents classification solutions that contain an ensemble of multiple classification models
34  /// </summary>
[17097]35  [StorableType("4CDD22EE-B53D-4899-A77E-C503FF9EBC8E")]
[5816]36  [Item("Classification Ensemble Solution", "A classification solution that contains an ensemble of multiple classification models")]
[12708]37  [Creatable(CreatableAttribute.Categories.DataAnalysisEnsembles, Priority = 110)]
[8724]38  public sealed class ClassificationEnsembleSolution : ClassificationSolutionBase, IClassificationEnsembleSolution {
[8167]39    private readonly Dictionary<int, double> trainingEvaluationCache = new Dictionary<int, double>();
40    private readonly Dictionary<int, double> testEvaluationCache = new Dictionary<int, double>();
[8724]41    private readonly Dictionary<int, double> evaluationCache = new Dictionary<int, double>();
[8153]42
[6239]43    public new IClassificationEnsembleModel Model {
44      get { return (IClassificationEnsembleModel)base.Model; }
45    }
[6666]46    public new ClassificationEnsembleProblemData ProblemData {
47      get { return (ClassificationEnsembleProblemData)base.ProblemData; }
48      set { base.ProblemData = value; }
49    }
[6239]50
[13049]51    [Storable]
[6613]52    private readonly ItemCollection<IClassificationSolution> classificationSolutions;
53    public IItemCollection<IClassificationSolution> ClassificationSolutions {
54      get { return classificationSolutions; }
55    }
56
[5816]57    [Storable]
[6239]58    private Dictionary<IClassificationModel, IntRange> trainingPartitions;
59    [Storable]
60    private Dictionary<IClassificationModel, IntRange> testPartitions;
61
[6613]62    [StorableConstructor]
[17097]63    private ClassificationEnsembleSolution(StorableConstructorFlag _) : base(_) {
[6613]64      classificationSolutions = new ItemCollection<IClassificationSolution>();
65    }
66    [StorableHook(HookType.AfterDeserialization)]
67    private void AfterDeserialization() {
[13049]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;
[6239]75
[13049]76          classificationSolutions.Add(model.CreateClassificationSolution(problemData));
77        }
[6613]78      }
79      RegisterClassificationSolutionsEventHandler();
80    }
81
[6592]82    private ClassificationEnsembleSolution(ClassificationEnsembleSolution original, Cloner cloner)
[5816]83      : base(original, cloner) {
[6239]84      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
85      testPartitions = new Dictionary<IClassificationModel, IntRange>();
[6302]86      foreach (var pair in original.trainingPartitions) {
87        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
[6239]88      }
[6302]89      foreach (var pair in original.testPartitions) {
90        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
91      }
[6613]92
[8174]93      trainingEvaluationCache = new Dictionary<int, double>(original.ProblemData.TrainingIndices.Count());
94      testEvaluationCache = new Dictionary<int, double>(original.ProblemData.TestIndices.Count());
95
[6613]96      classificationSolutions = cloner.Clone(original.classificationSolutions);
97      RegisterClassificationSolutionsEventHandler();
[5816]98    }
[6613]99
[6666]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
[8528]109    public ClassificationEnsembleSolution(IClassificationProblemData problemData) :
110      this(Enumerable.Empty<IClassificationModel>(), problemData) { }
111
[6239]112    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData)
[6613]113      : this(models, problemData,
114             models.Select(m => (IntRange)problemData.TrainingPartition.Clone()),
115             models.Select(m => (IntRange)problemData.TestPartition.Clone())
116      ) { }
[5816]117
[6239]118    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions)
[6613]119      : base(new ClassificationEnsembleModel(Enumerable.Empty<IClassificationModel>()), new ClassificationEnsembleProblemData(problemData)) {
[6239]120      this.trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
121      this.testPartitions = new Dictionary<IClassificationModel, IntRange>();
[6613]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
[8174]142      trainingEvaluationCache = new Dictionary<int, double>(problemData.TrainingIndices.Count());
143      testEvaluationCache = new Dictionary<int, double>(problemData.TestIndices.Count());
144
[6613]145      RegisterClassificationSolutionsEventHandler();
146      classificationSolutions.AddRange(solutions);
[6239]147    }
148
[5816]149    public override IDeepCloneable Clone(Cloner cloner) {
150      return new ClassificationEnsembleSolution(this, cloner);
151    }
[6613]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    }
[5816]157
[6589]158
[6613]159    #region Evaluation
[8724]160    public override IEnumerable<double> EstimatedClassValues {
161      get { return GetEstimatedClassValues(Enumerable.Range(0, ProblemData.Dataset.Rows)); }
162    }
163
[6239]164    public override IEnumerable<double> EstimatedTrainingClassValues {
165      get {
[8139]166        var rows = ProblemData.TrainingIndices;
[8167]167        var rowsToEvaluate = rows.Except(trainingEvaluationCache.Keys);
[8153]168        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
169        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, (r, m) => RowIsTrainingForModel(r, m) && !RowIsTestForModel(r, m)).GetEnumerator();
[5816]170
[8153]171        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
[8167]172          trainingEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
[6239]173        }
[8153]174
[8167]175        return rows.Select(row => trainingEvaluationCache[row]);
[6239]176      }
177    }
178
179    public override IEnumerable<double> EstimatedTestClassValues {
180      get {
[8139]181        var rows = ProblemData.TestIndices;
[8167]182        var rowsToEvaluate = rows.Except(testEvaluationCache.Keys);
[8153]183        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
184        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, RowIsTestForModel).GetEnumerator();
[6239]185
[8153]186        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
[8167]187          testEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
[8153]188        }
[6239]189
[8167]190        return rows.Select(row => testEvaluationCache[row]);
[6239]191      }
192    }
193
[8153]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
[6254]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
[6239]221    public override IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows) {
[8167]222      var rowsToEvaluate = rows.Except(evaluationCache.Keys);
[8153]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()) {
[8167]229        evaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
[8153]230      }
231
[8167]232      return rows.Select(row => evaluationCache[row]);
[6239]233    }
234
[12702]235    public IEnumerable<IEnumerable<double>> GetEstimatedClassValueVectors(IDataset dataset, IEnumerable<int> rows) {
[6982]236      if (!Model.Models.Any()) yield break;
[6239]237      var estimatedValuesEnumerators = (from model in Model.Models
[5816]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
[6239]247    private double AggregateEstimatedClassValues(IEnumerable<double> estimatedClassValues) {
248      return estimatedClassValues
249      .GroupBy(x => x)
250      .OrderBy(g => -g.Count())
251      .Select(g => g.Key)
[6254]252      .DefaultIfEmpty(double.NaN)
[6239]253      .First();
[5816]254    }
[6613]255    #endregion
[6520]256
[6666]257    protected override void OnProblemDataChanged() {
[8167]258      trainingEvaluationCache.Clear();
259      testEvaluationCache.Clear();
260      evaluationCache.Clear();
[8153]261
[6666]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
[6613]288    public void AddClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
289      classificationSolutions.AddRange(solutions);
[8153]290
[8167]291      trainingEvaluationCache.Clear();
292      testEvaluationCache.Clear();
293      evaluationCache.Clear();
[6613]294    }
295    public void RemoveClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
296      classificationSolutions.RemoveRange(solutions);
[8153]297
[8167]298      trainingEvaluationCache.Clear();
299      testEvaluationCache.Clear();
300      evaluationCache.Clear();
[6613]301    }
[6520]302
[6613]303    private void classificationSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
304      foreach (var solution in e.Items) AddClassificationSolution(solution);
[6520]305      RecalculateResults();
306    }
[6613]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    }
[6520]316
[6613]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;
[8153]322
[8167]323      trainingEvaluationCache.Clear();
324      testEvaluationCache.Clear();
325      evaluationCache.Clear();
[6613]326    }
[6520]327
[6613]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);
[8153]333
[8167]334      trainingEvaluationCache.Clear();
335      testEvaluationCache.Clear();
336      evaluationCache.Clear();
[6520]337    }
[5816]338  }
339}
Note: See TracBrowser for help on using the repository browser.