Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6415 was 6302, checked in by gkronber, 14 years ago

#1450: fixed cloning bug and a problem in the regression line chart view.

File size: 8.5 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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27using HeuristicLab.Data;
28using System;
29
30namespace HeuristicLab.Problems.DataAnalysis {
31  /// <summary>
32  /// Represents classification solutions that contain an ensemble of multiple classification models
33  /// </summary>
34  [StorableClass]
35  [Item("Classification Ensemble Solution", "A classification solution that contains an ensemble of multiple classification models")]
36  // [Creatable("Data Analysis")]
37  public class ClassificationEnsembleSolution : ClassificationSolution, IClassificationEnsembleSolution {
38
39    public new IClassificationEnsembleModel Model {
40      set { base.Model = value; }
41      get { return (IClassificationEnsembleModel)base.Model; }
42    }
43
44    [Storable]
45    private Dictionary<IClassificationModel, IntRange> trainingPartitions;
46    [Storable]
47    private Dictionary<IClassificationModel, IntRange> testPartitions;
48
49
50    [StorableConstructor]
51    protected ClassificationEnsembleSolution(bool deserializing) : base(deserializing) { }
52    protected ClassificationEnsembleSolution(ClassificationEnsembleSolution original, Cloner cloner)
53      : base(original, cloner) {
54      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
55      testPartitions = new Dictionary<IClassificationModel, IntRange>();
56      foreach (var pair in original.trainingPartitions) {
57        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
58      }
59      foreach (var pair in original.testPartitions) {
60        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
61      }
62      RecalculateResults();
63    }
64    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData)
65      : base(new ClassificationEnsembleModel(models), new ClassificationEnsembleProblemData(problemData)) {
66      this.name = ItemName;
67      this.description = ItemDescription;
68      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
69      testPartitions = new Dictionary<IClassificationModel, IntRange>();
70      foreach (var model in models) {
71        trainingPartitions[model] = (IntRange)problemData.TrainingPartition.Clone();
72        testPartitions[model] = (IntRange)problemData.TestPartition.Clone();
73      }
74      RecalculateResults();
75    }
76
77    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions)
78      : base(new ClassificationEnsembleModel(models), new ClassificationEnsembleProblemData(problemData)) {
79      this.trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
80      this.testPartitions = new Dictionary<IClassificationModel, IntRange>();
81      var modelEnumerator = models.GetEnumerator();
82      var trainingPartitionEnumerator = trainingPartitions.GetEnumerator();
83      var testPartitionEnumerator = testPartitions.GetEnumerator();
84      while (modelEnumerator.MoveNext() & trainingPartitionEnumerator.MoveNext() & testPartitionEnumerator.MoveNext()) {
85        this.trainingPartitions[modelEnumerator.Current] = (IntRange)trainingPartitionEnumerator.Current.Clone();
86        this.testPartitions[modelEnumerator.Current] = (IntRange)testPartitionEnumerator.Current.Clone();
87      }
88      if (modelEnumerator.MoveNext() | trainingPartitionEnumerator.MoveNext() | testPartitionEnumerator.MoveNext()) {
89        throw new ArgumentException();
90      }
91      RecalculateResults();
92    }
93
94    public override IDeepCloneable Clone(Cloner cloner) {
95      return new ClassificationEnsembleSolution(this, cloner);
96    }
97
98    public override IEnumerable<double> EstimatedTrainingClassValues {
99      get {
100        var rows = ProblemData.TrainingIndizes;
101        var estimatedValuesEnumerators = (from model in Model.Models
102                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
103                                         .ToList();
104        var rowsEnumerator = rows.GetEnumerator();
105        // aggregate to make sure that MoveNext is called for all enumerators
106        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
107          int currentRow = rowsEnumerator.Current;
108
109          var selectedEnumerators = from pair in estimatedValuesEnumerators
110                                    where RowIsTrainingForModel(currentRow, pair.Model) && !RowIsTestForModel(currentRow, pair.Model)
111                                    select pair.EstimatedValuesEnumerator;
112          yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
113        }
114      }
115    }
116
117    public override IEnumerable<double> EstimatedTestClassValues {
118      get {
119        var rows = ProblemData.TestIndizes;
120        var estimatedValuesEnumerators = (from model in Model.Models
121                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
122                                         .ToList();
123        var rowsEnumerator = ProblemData.TestIndizes.GetEnumerator();
124        // aggregate to make sure that MoveNext is called for all enumerators
125        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
126          int currentRow = rowsEnumerator.Current;
127
128          var selectedEnumerators = from pair in estimatedValuesEnumerators
129                                    where RowIsTestForModel(currentRow, pair.Model)
130                                    select pair.EstimatedValuesEnumerator;
131
132          yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
133        }
134      }
135    }
136
137    private bool RowIsTrainingForModel(int currentRow, IClassificationModel model) {
138      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
139              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
140    }
141
142    private bool RowIsTestForModel(int currentRow, IClassificationModel model) {
143      return testPartitions == null || !testPartitions.ContainsKey(model) ||
144              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
145    }
146
147    public override IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows) {
148      return from xs in GetEstimatedClassValueVectors(ProblemData.Dataset, rows)
149             select AggregateEstimatedClassValues(xs);
150    }
151
152    public IEnumerable<IEnumerable<double>> GetEstimatedClassValueVectors(Dataset dataset, IEnumerable<int> rows) {
153      var estimatedValuesEnumerators = (from model in Model.Models
154                                        select model.GetEstimatedClassValues(dataset, rows).GetEnumerator())
155                                       .ToList();
156
157      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
158        yield return from enumerator in estimatedValuesEnumerators
159                     select enumerator.Current;
160      }
161    }
162
163    private double AggregateEstimatedClassValues(IEnumerable<double> estimatedClassValues) {
164      return estimatedClassValues
165      .GroupBy(x => x)
166      .OrderBy(g => -g.Count())
167      .Select(g => g.Key)
168      .DefaultIfEmpty(double.NaN)
169      .First();
170    }
171  }
172}
Note: See TracBrowser for help on using the repository browser.