Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10879 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

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