Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6592 was 6592, checked in by mkommend, 13 years ago

#1600: Changed ensemble solutions to sealed classed.

File size: 9.9 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;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
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 sealed 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    private ClassificationEnsembleSolution(bool deserializing) : base(deserializing) { }
52    private 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      AddModelsAndPartitions(models,
82        trainingPartitions,
83        testPartitions);
84      RecalculateResults();
85    }
86
87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new ClassificationEnsembleSolution(this, cloner);
89    }
90
91    protected override void RecalculateResults() {
92      CalculateResults();
93    }
94
95    public override IEnumerable<double> EstimatedTrainingClassValues {
96      get {
97        var rows = ProblemData.TrainingIndizes;
98        var estimatedValuesEnumerators = (from model in Model.Models
99                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
100                                         .ToList();
101        var rowsEnumerator = rows.GetEnumerator();
102        // aggregate to make sure that MoveNext is called for all enumerators
103        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
104          int currentRow = rowsEnumerator.Current;
105
106          var selectedEnumerators = from pair in estimatedValuesEnumerators
107                                    where RowIsTrainingForModel(currentRow, pair.Model) && !RowIsTestForModel(currentRow, pair.Model)
108                                    select pair.EstimatedValuesEnumerator;
109          yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
110        }
111      }
112    }
113
114    public override IEnumerable<double> EstimatedTestClassValues {
115      get {
116        var rows = ProblemData.TestIndizes;
117        var estimatedValuesEnumerators = (from model in Model.Models
118                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedClassValues(ProblemData.Dataset, rows).GetEnumerator() })
119                                         .ToList();
120        var rowsEnumerator = ProblemData.TestIndizes.GetEnumerator();
121        // aggregate to make sure that MoveNext is called for all enumerators
122        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
123          int currentRow = rowsEnumerator.Current;
124
125          var selectedEnumerators = from pair in estimatedValuesEnumerators
126                                    where RowIsTestForModel(currentRow, pair.Model)
127                                    select pair.EstimatedValuesEnumerator;
128
129          yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
130        }
131      }
132    }
133
134    private bool RowIsTrainingForModel(int currentRow, IClassificationModel model) {
135      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
136              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
137    }
138
139    private bool RowIsTestForModel(int currentRow, IClassificationModel model) {
140      return testPartitions == null || !testPartitions.ContainsKey(model) ||
141              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
142    }
143
144    public override IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows) {
145      return from xs in GetEstimatedClassValueVectors(ProblemData.Dataset, rows)
146             select AggregateEstimatedClassValues(xs);
147    }
148
149    public IEnumerable<IEnumerable<double>> GetEstimatedClassValueVectors(Dataset dataset, IEnumerable<int> rows) {
150      var estimatedValuesEnumerators = (from model in Model.Models
151                                        select model.GetEstimatedClassValues(dataset, rows).GetEnumerator())
152                                       .ToList();
153
154      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
155        yield return from enumerator in estimatedValuesEnumerators
156                     select enumerator.Current;
157      }
158    }
159
160    private double AggregateEstimatedClassValues(IEnumerable<double> estimatedClassValues) {
161      return estimatedClassValues
162      .GroupBy(x => x)
163      .OrderBy(g => -g.Count())
164      .Select(g => g.Key)
165      .DefaultIfEmpty(double.NaN)
166      .First();
167    }
168
169    public void AddModelsAndPartitions(IEnumerable<IClassificationSolution> solutions) {
170      foreach (var solution in solutions) {
171        var ensembleSolution = solution as ClassificationEnsembleSolution;
172        if (ensembleSolution != null) {
173          var data = from m in ensembleSolution.Model.Models
174                     let train = ensembleSolution.trainingPartitions[m]
175                     let test = ensembleSolution.testPartitions[m]
176                     select new { m, train, test };
177
178          foreach (var d in data) {
179            Model.Add(d.m);
180            trainingPartitions[d.m] = (IntRange)d.train.Clone();
181            testPartitions[d.m] = (IntRange)d.test.Clone();
182          }
183        } else {
184          Model.Add(solution.Model);
185          trainingPartitions[solution.Model] = (IntRange)solution.ProblemData.TrainingPartition.Clone();
186          testPartitions[solution.Model] = (IntRange)solution.ProblemData.TestPartition.Clone();
187        }
188      }
189
190      RecalculateResults();
191    }
192
193    private void AddModelsAndPartitions(IEnumerable<IClassificationModel> models, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions) {
194      var modelEnumerator = models.GetEnumerator();
195      var trainingPartitionEnumerator = trainingPartitions.GetEnumerator();
196      var testPartitionEnumerator = testPartitions.GetEnumerator();
197
198      while (modelEnumerator.MoveNext() & trainingPartitionEnumerator.MoveNext() & testPartitionEnumerator.MoveNext()) {
199        this.trainingPartitions[modelEnumerator.Current] = (IntRange)trainingPartitionEnumerator.Current.Clone();
200        this.testPartitions[modelEnumerator.Current] = (IntRange)testPartitionEnumerator.Current.Clone();
201      }
202      if (modelEnumerator.MoveNext() | trainingPartitionEnumerator.MoveNext() | testPartitionEnumerator.MoveNext()) {
203        throw new ArgumentException();
204      }
205    }
206  }
207}
Note: See TracBrowser for help on using the repository browser.