Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17912 was 17835, checked in by bburlacu, 4 years ago

#3102: Add ClassificationProblemData constructor that explicitly takes class names and positive class value arguments, adapt code.

File size: 15.7 KB
RevLine 
[5816]1#region License Information
2/* HeuristicLab
[17180]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;
[16565]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>
[16565]35  [StorableType("4CDD22EE-B53D-4899-A77E-C503FF9EBC8E")]
[5816]36  [Item("Classification Ensemble Solution", "A classification solution that contains an ensemble of multiple classification models")]
[12504]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
[12816]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]
[16565]63    private ClassificationEnsembleSolution(StorableConstructorFlag _) : base(_) {
[6613]64      classificationSolutions = new ItemCollection<IClassificationSolution>();
65    }
66    [StorableHook(HookType.AfterDeserialization)]
67    private void AfterDeserialization() {
[12816]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
[12816]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
[12509]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
[17835]262      IClassificationProblemData problemData = new ClassificationProblemData(ProblemData);
[6666]263
264      foreach (var solution in ClassificationSolutions) {
265        if (solution is ClassificationEnsembleSolution)
266          solution.ProblemData = ProblemData;
267        else
268          solution.ProblemData = problemData;
269      }
270      foreach (var trainingPartition in trainingPartitions.Values) {
271        trainingPartition.Start = ProblemData.TrainingPartition.Start;
272        trainingPartition.End = ProblemData.TrainingPartition.End;
273      }
274      foreach (var testPartition in testPartitions.Values) {
275        testPartition.Start = ProblemData.TestPartition.Start;
276        testPartition.End = ProblemData.TestPartition.End;
277      }
278
279      base.OnProblemDataChanged();
280    }
281
[6613]282    public void AddClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
283      classificationSolutions.AddRange(solutions);
[8153]284
[8167]285      trainingEvaluationCache.Clear();
286      testEvaluationCache.Clear();
287      evaluationCache.Clear();
[6613]288    }
289    public void RemoveClassificationSolutions(IEnumerable<IClassificationSolution> solutions) {
290      classificationSolutions.RemoveRange(solutions);
[8153]291
[8167]292      trainingEvaluationCache.Clear();
293      testEvaluationCache.Clear();
294      evaluationCache.Clear();
[6613]295    }
[6520]296
[6613]297    private void classificationSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
298      foreach (var solution in e.Items) AddClassificationSolution(solution);
[6520]299      RecalculateResults();
300    }
[6613]301    private void classificationSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
302      foreach (var solution in e.Items) RemoveClassificationSolution(solution);
303      RecalculateResults();
304    }
305    private void classificationSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IClassificationSolution> e) {
306      foreach (var solution in e.OldItems) RemoveClassificationSolution(solution);
307      foreach (var solution in e.Items) AddClassificationSolution(solution);
308      RecalculateResults();
309    }
[6520]310
[6613]311    private void AddClassificationSolution(IClassificationSolution solution) {
312      if (Model.Models.Contains(solution.Model)) throw new ArgumentException();
313      Model.Add(solution.Model);
314      trainingPartitions[solution.Model] = solution.ProblemData.TrainingPartition;
315      testPartitions[solution.Model] = solution.ProblemData.TestPartition;
[8153]316
[8167]317      trainingEvaluationCache.Clear();
318      testEvaluationCache.Clear();
319      evaluationCache.Clear();
[6613]320    }
[6520]321
[6613]322    private void RemoveClassificationSolution(IClassificationSolution solution) {
323      if (!Model.Models.Contains(solution.Model)) throw new ArgumentException();
324      Model.Remove(solution.Model);
325      trainingPartitions.Remove(solution.Model);
326      testPartitions.Remove(solution.Model);
[8153]327
[8167]328      trainingEvaluationCache.Clear();
329      testEvaluationCache.Clear();
330      evaluationCache.Clear();
[6520]331    }
[5816]332  }
333}
Note: See TracBrowser for help on using the repository browser.