Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1600: Changed ensemble solutions to sealed classed.

File size: 9.9 KB
RevLine 
[5816]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
[6589]22using System;
[5816]23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
[6589]27using HeuristicLab.Data;
[5816]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")]
[6592]37  public sealed class ClassificationEnsembleSolution : ClassificationSolution, IClassificationEnsembleSolution {
[5816]38
[6239]39    public new IClassificationEnsembleModel Model {
40      set { base.Model = value; }
41      get { return (IClassificationEnsembleModel)base.Model; }
42    }
43
[5816]44    [Storable]
[6239]45    private Dictionary<IClassificationModel, IntRange> trainingPartitions;
46    [Storable]
47    private Dictionary<IClassificationModel, IntRange> testPartitions;
48
49
[5816]50    [StorableConstructor]
[6592]51    private ClassificationEnsembleSolution(bool deserializing) : base(deserializing) { }
52    private ClassificationEnsembleSolution(ClassificationEnsembleSolution original, Cloner cloner)
[5816]53      : base(original, cloner) {
[6239]54      trainingPartitions = new Dictionary<IClassificationModel, IntRange>();
55      testPartitions = new Dictionary<IClassificationModel, IntRange>();
[6302]56      foreach (var pair in original.trainingPartitions) {
57        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
[6239]58      }
[6302]59      foreach (var pair in original.testPartitions) {
60        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
61      }
[6239]62      RecalculateResults();
[5816]63    }
[6239]64    public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData)
65      : base(new ClassificationEnsembleModel(models), new ClassificationEnsembleProblemData(problemData)) {
[5816]66      this.name = ItemName;
67      this.description = ItemDescription;
[6239]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();
[5816]75    }
76
[6239]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>();
[6590]81      AddModelsAndPartitions(models,
[6520]82        trainingPartitions,
83        testPartitions);
[6239]84      RecalculateResults();
85    }
86
[5816]87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new ClassificationEnsembleSolution(this, cloner);
89    }
90
[6589]91    protected override void RecalculateResults() {
92      CalculateResults();
93    }
94
[6239]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;
[5816]105
[6239]106          var selectedEnumerators = from pair in estimatedValuesEnumerators
[6254]107                                    where RowIsTrainingForModel(currentRow, pair.Model) && !RowIsTestForModel(currentRow, pair.Model)
[6239]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
[6254]126                                    where RowIsTestForModel(currentRow, pair.Model)
[6239]127                                    select pair.EstimatedValuesEnumerator;
128
129          yield return AggregateEstimatedClassValues(selectedEnumerators.Select(x => x.Current));
130        }
131      }
132    }
133
[6254]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
[6239]144    public override IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows) {
145      return from xs in GetEstimatedClassValueVectors(ProblemData.Dataset, rows)
146             select AggregateEstimatedClassValues(xs);
147    }
148
[5816]149    public IEnumerable<IEnumerable<double>> GetEstimatedClassValueVectors(Dataset dataset, IEnumerable<int> rows) {
[6239]150      var estimatedValuesEnumerators = (from model in Model.Models
[5816]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
[6239]160    private double AggregateEstimatedClassValues(IEnumerable<double> estimatedClassValues) {
161      return estimatedClassValues
162      .GroupBy(x => x)
163      .OrderBy(g => -g.Count())
164      .Select(g => g.Key)
[6254]165      .DefaultIfEmpty(double.NaN)
[6239]166      .First();
[5816]167    }
[6520]168
[6574]169    public void AddModelsAndPartitions(IEnumerable<IClassificationSolution> solutions) {
[6520]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
[6590]193    private void AddModelsAndPartitions(IEnumerable<IClassificationModel> models, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions) {
[6520]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    }
[5816]206  }
207}
Note: See TracBrowser for help on using the repository browser.