Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionEnsembleSolution.cs @ 6574

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

#1579: Corrected typo in EnsembleSolution.

File size: 9.3 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 System;
28using HeuristicLab.Data;
29
30namespace HeuristicLab.Problems.DataAnalysis {
31  /// <summary>
32  /// Represents regression solutions that contain an ensemble of multiple regression models
33  /// </summary>
34  [StorableClass]
35  [Item("Regression Ensemble Solution", "A regression solution that contains an ensemble of multiple regression models")]
36  // [Creatable("Data Analysis")]
37  public class RegressionEnsembleSolution : RegressionSolution, IRegressionEnsembleSolution {
38    public new IRegressionEnsembleModel Model {
39      get { return (IRegressionEnsembleModel)base.Model; }
40    }
41
42    [Storable]
43    private Dictionary<IRegressionModel, IntRange> trainingPartitions;
44    [Storable]
45    private Dictionary<IRegressionModel, IntRange> testPartitions;
46
47    [StorableConstructor]
48    protected RegressionEnsembleSolution(bool deserializing) : base(deserializing) { }
49    protected RegressionEnsembleSolution(RegressionEnsembleSolution original, Cloner cloner)
50      : base(original, cloner) {
51      trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
52      testPartitions = new Dictionary<IRegressionModel, IntRange>();
53      foreach (var pair in original.trainingPartitions) {
54        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
55      }
56      foreach (var pair in original.testPartitions) {
57        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
58      }
59      RecalculateResults();
60    }
61
62    public RegressionEnsembleSolution(IEnumerable<IRegressionModel> models, IRegressionProblemData problemData)
63      : base(new RegressionEnsembleModel(models), new RegressionEnsembleProblemData(problemData)) {
64      trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
65      testPartitions = new Dictionary<IRegressionModel, IntRange>();
66      AddModelsAndParitions(models,
67        from m in models select (IntRange)problemData.TrainingPartition.Clone(),
68        from m in models select (IntRange)problemData.TestPartition.Clone());
69      RecalculateResults();
70    }
71
72    public RegressionEnsembleSolution(IEnumerable<IRegressionModel> models, IRegressionProblemData problemData, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions)
73      : base(new RegressionEnsembleModel(models), new RegressionEnsembleProblemData(problemData)) {
74      this.trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
75      this.testPartitions = new Dictionary<IRegressionModel, IntRange>();
76      AddModelsAndParitions(models, trainingPartitions, testPartitions);
77      RecalculateResults();
78    }
79
80    public override IDeepCloneable Clone(Cloner cloner) {
81      return new RegressionEnsembleSolution(this, cloner);
82    }
83
84    public override IEnumerable<double> EstimatedTrainingValues {
85      get {
86        var rows = ProblemData.TrainingIndizes;
87        var estimatedValuesEnumerators = (from model in Model.Models
88                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedValues(ProblemData.Dataset, rows).GetEnumerator() })
89                                         .ToList();
90        var rowsEnumerator = rows.GetEnumerator();
91        // aggregate to make sure that MoveNext is called for all enumerators
92        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
93          int currentRow = rowsEnumerator.Current;
94
95          var selectedEnumerators = from pair in estimatedValuesEnumerators
96                                    where RowIsTrainingForModel(currentRow, pair.Model) && !RowIsTestForModel(currentRow, pair.Model)
97                                    select pair.EstimatedValuesEnumerator;
98          yield return AggregateEstimatedValues(selectedEnumerators.Select(x => x.Current));
99        }
100      }
101    }
102
103    public override IEnumerable<double> EstimatedTestValues {
104      get {
105        var rows = ProblemData.TestIndizes;
106        var estimatedValuesEnumerators = (from model in Model.Models
107                                          select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedValues(ProblemData.Dataset, rows).GetEnumerator() })
108                                         .ToList();
109        var rowsEnumerator = ProblemData.TestIndizes.GetEnumerator();
110        // aggregate to make sure that MoveNext is called for all enumerators
111        while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
112          int currentRow = rowsEnumerator.Current;
113
114          var selectedEnumerators = from pair in estimatedValuesEnumerators
115                                    where RowIsTestForModel(currentRow, pair.Model)
116                                    select pair.EstimatedValuesEnumerator;
117
118          yield return AggregateEstimatedValues(selectedEnumerators.Select(x => x.Current));
119        }
120      }
121    }
122
123    private bool RowIsTrainingForModel(int currentRow, IRegressionModel model) {
124      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
125              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
126    }
127
128    private bool RowIsTestForModel(int currentRow, IRegressionModel model) {
129      return testPartitions == null || !testPartitions.ContainsKey(model) ||
130              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
131    }
132
133    public override IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows) {
134      return from xs in GetEstimatedValueVectors(ProblemData.Dataset, rows)
135             select AggregateEstimatedValues(xs);
136    }
137
138    public IEnumerable<IEnumerable<double>> GetEstimatedValueVectors(Dataset dataset, IEnumerable<int> rows) {
139      var estimatedValuesEnumerators = (from model in Model.Models
140                                        select model.GetEstimatedValues(dataset, rows).GetEnumerator())
141                                       .ToList();
142
143      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
144        yield return from enumerator in estimatedValuesEnumerators
145                     select enumerator.Current;
146      }
147    }
148
149    private double AggregateEstimatedValues(IEnumerable<double> estimatedValues) {
150      return estimatedValues.DefaultIfEmpty(double.NaN).Average();
151    }
152
153
154    public void AddModelsAndPartitions(IEnumerable<IRegressionSolution> solutions) {
155      foreach (var solution in solutions) {
156        var ensembleSolution = solution as RegressionEnsembleSolution;
157        if (ensembleSolution != null) {
158          var data = from m in ensembleSolution.Model.Models
159                     let train = ensembleSolution.trainingPartitions[m]
160                     let test = ensembleSolution.testPartitions[m]
161                     select new { m, train, test };
162
163          foreach (var d in data) {
164            Model.Add(d.m);
165            trainingPartitions[d.m] = (IntRange)d.train.Clone();
166            testPartitions[d.m] = (IntRange)d.test.Clone();
167          }
168        } else {
169          Model.Add(solution.Model);
170          trainingPartitions[solution.Model] = (IntRange)solution.ProblemData.TrainingPartition.Clone();
171          testPartitions[solution.Model] = (IntRange)solution.ProblemData.TestPartition.Clone();
172        }
173      }
174
175      RecalculateResults();
176    }
177
178    private void AddModelsAndParitions(IEnumerable<IRegressionModel> models, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions) {
179      var modelEnumerator = models.GetEnumerator();
180      var trainingPartitionEnumerator = trainingPartitions.GetEnumerator();
181      var testPartitionEnumerator = testPartitions.GetEnumerator();
182
183      while (modelEnumerator.MoveNext() & trainingPartitionEnumerator.MoveNext() & testPartitionEnumerator.MoveNext()) {
184        this.trainingPartitions[modelEnumerator.Current] = (IntRange)trainingPartitionEnumerator.Current.Clone();
185        this.testPartitions[modelEnumerator.Current] = (IntRange)testPartitionEnumerator.Current.Clone();
186      }
187      if (modelEnumerator.MoveNext() | trainingPartitionEnumerator.MoveNext() | testPartitionEnumerator.MoveNext()) {
188        throw new ArgumentException();
189      }
190    }
191  }
192}
Note: See TracBrowser for help on using the repository browser.