Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8723 was 8723, checked in by mkommend, 12 years ago

#1964: Added new results to symbolic classification and regression solutions. Additionally, the way results are calculated was refactored and unified.

File size: 15.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Problems.DataAnalysis {
32  /// <summary>
33  /// Represents regression solutions that contain an ensemble of multiple regression models
34  /// </summary>
35  [StorableClass]
36  [Item("Regression Ensemble Solution", "A regression solution that contains an ensemble of multiple regression models")]
37  [Creatable("Data Analysis - Ensembles")]
38  public sealed class RegressionEnsembleSolution : RegressionSolution, IRegressionEnsembleSolution {
39    private readonly Dictionary<int, double> trainingEvaluationCache = new Dictionary<int, double>();
40    private readonly Dictionary<int, double> testEvaluationCache = new Dictionary<int, double>();
41
42    public new IRegressionEnsembleModel Model {
43      get { return (IRegressionEnsembleModel)base.Model; }
44    }
45
46    public new RegressionEnsembleProblemData ProblemData {
47      get { return (RegressionEnsembleProblemData)base.ProblemData; }
48      set { base.ProblemData = value; }
49    }
50
51    private readonly ItemCollection<IRegressionSolution> regressionSolutions;
52    public IItemCollection<IRegressionSolution> RegressionSolutions {
53      get { return regressionSolutions; }
54    }
55
56    [Storable]
57    private readonly Dictionary<IRegressionModel, IntRange> trainingPartitions;
58    [Storable]
59    private readonly Dictionary<IRegressionModel, IntRange> testPartitions;
60
61    [StorableConstructor]
62    private RegressionEnsembleSolution(bool deserializing)
63      : base(deserializing) {
64      regressionSolutions = new ItemCollection<IRegressionSolution>();
65    }
66    [StorableHook(HookType.AfterDeserialization)]
67    private void AfterDeserialization() {
68      foreach (var model in Model.Models) {
69        IRegressionProblemData problemData = (IRegressionProblemData)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;
74
75        regressionSolutions.Add(model.CreateRegressionSolution(problemData));
76      }
77      RegisterRegressionSolutionsEventHandler();
78    }
79
80    private RegressionEnsembleSolution(RegressionEnsembleSolution original, Cloner cloner)
81      : base(original, cloner) {
82      trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
83      testPartitions = new Dictionary<IRegressionModel, IntRange>();
84      foreach (var pair in original.trainingPartitions) {
85        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
86      }
87      foreach (var pair in original.testPartitions) {
88        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
89      }
90
91      trainingEvaluationCache = new Dictionary<int, double>(original.ProblemData.TrainingIndices.Count());
92      testEvaluationCache = new Dictionary<int, double>(original.ProblemData.TestIndices.Count());
93
94      regressionSolutions = cloner.Clone(original.regressionSolutions);
95      RegisterRegressionSolutionsEventHandler();
96    }
97
98    public RegressionEnsembleSolution()
99      : base(new RegressionEnsembleModel(), RegressionEnsembleProblemData.EmptyProblemData) {
100      trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
101      testPartitions = new Dictionary<IRegressionModel, IntRange>();
102      regressionSolutions = new ItemCollection<IRegressionSolution>();
103
104      RegisterRegressionSolutionsEventHandler();
105    }
106
107    public RegressionEnsembleSolution(IRegressionProblemData problemData)
108      : this(Enumerable.Empty<IRegressionModel>(), problemData) {
109    }
110
111    public RegressionEnsembleSolution(IEnumerable<IRegressionModel> models, IRegressionProblemData problemData)
112      : this(models, problemData,
113             models.Select(m => (IntRange)problemData.TrainingPartition.Clone()),
114             models.Select(m => (IntRange)problemData.TestPartition.Clone())
115      ) { }
116
117    public RegressionEnsembleSolution(IEnumerable<IRegressionModel> models, IRegressionProblemData problemData, IEnumerable<IntRange> trainingPartitions, IEnumerable<IntRange> testPartitions)
118      : base(new RegressionEnsembleModel(Enumerable.Empty<IRegressionModel>()), new RegressionEnsembleProblemData(problemData)) {
119      this.trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
120      this.testPartitions = new Dictionary<IRegressionModel, IntRange>();
121      this.regressionSolutions = new ItemCollection<IRegressionSolution>();
122
123      List<IRegressionSolution> solutions = new List<IRegressionSolution>();
124      var modelEnumerator = models.GetEnumerator();
125      var trainingPartitionEnumerator = trainingPartitions.GetEnumerator();
126      var testPartitionEnumerator = testPartitions.GetEnumerator();
127
128      while (modelEnumerator.MoveNext() & trainingPartitionEnumerator.MoveNext() & testPartitionEnumerator.MoveNext()) {
129        var p = (IRegressionProblemData)problemData.Clone();
130        p.TrainingPartition.Start = trainingPartitionEnumerator.Current.Start;
131        p.TrainingPartition.End = trainingPartitionEnumerator.Current.End;
132        p.TestPartition.Start = testPartitionEnumerator.Current.Start;
133        p.TestPartition.End = testPartitionEnumerator.Current.End;
134
135        solutions.Add(modelEnumerator.Current.CreateRegressionSolution(p));
136      }
137      if (modelEnumerator.MoveNext() | trainingPartitionEnumerator.MoveNext() | testPartitionEnumerator.MoveNext()) {
138        throw new ArgumentException();
139      }
140
141      trainingEvaluationCache = new Dictionary<int, double>(problemData.TrainingIndices.Count());
142      testEvaluationCache = new Dictionary<int, double>(problemData.TestIndices.Count());
143
144      RegisterRegressionSolutionsEventHandler();
145      regressionSolutions.AddRange(solutions);
146    }
147
148    public override IDeepCloneable Clone(Cloner cloner) {
149      return new RegressionEnsembleSolution(this, cloner);
150    }
151    private void RegisterRegressionSolutionsEventHandler() {
152      regressionSolutions.ItemsAdded += new CollectionItemsChangedEventHandler<IRegressionSolution>(regressionSolutions_ItemsAdded);
153      regressionSolutions.ItemsRemoved += new CollectionItemsChangedEventHandler<IRegressionSolution>(regressionSolutions_ItemsRemoved);
154      regressionSolutions.CollectionReset += new CollectionItemsChangedEventHandler<IRegressionSolution>(regressionSolutions_CollectionReset);
155    }
156
157    #region Evaluation
158    public override IEnumerable<double> EstimatedTrainingValues {
159      get {
160        var rows = ProblemData.TrainingIndices;
161        var rowsToEvaluate = rows.Except(trainingEvaluationCache.Keys);
162        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
163        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, (r, m) => RowIsTrainingForModel(r, m) && !RowIsTestForModel(r, m)).GetEnumerator();
164
165        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
166          trainingEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
167        }
168
169        return rows.Select(row => trainingEvaluationCache[row]);
170      }
171    }
172
173    public override IEnumerable<double> EstimatedTestValues {
174      get {
175        var rows = ProblemData.TestIndices;
176        var rowsToEvaluate = rows.Except(testEvaluationCache.Keys);
177        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
178        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, RowIsTestForModel).GetEnumerator();
179
180        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
181          testEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
182        }
183
184        return rows.Select(row => testEvaluationCache[row]);
185      }
186    }
187
188    private IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows, Func<int, IRegressionModel, bool> modelSelectionPredicate) {
189      var estimatedValuesEnumerators = (from model in Model.Models
190                                        select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedValues(ProblemData.Dataset, rows).GetEnumerator() })
191                                       .ToList();
192      var rowsEnumerator = rows.GetEnumerator();
193      // aggregate to make sure that MoveNext is called for all enumerators
194      while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
195        int currentRow = rowsEnumerator.Current;
196
197        var selectedEnumerators = from pair in estimatedValuesEnumerators
198                                  where modelSelectionPredicate(currentRow, pair.Model)
199                                  select pair.EstimatedValuesEnumerator;
200
201        yield return AggregateEstimatedValues(selectedEnumerators.Select(x => x.Current));
202      }
203    }
204
205    private bool RowIsTrainingForModel(int currentRow, IRegressionModel model) {
206      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
207              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
208    }
209
210    private bool RowIsTestForModel(int currentRow, IRegressionModel model) {
211      return testPartitions == null || !testPartitions.ContainsKey(model) ||
212              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
213    }
214
215    public override IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows) {
216      var rowsToEvaluate = rows.Except(evaluationCache.Keys);
217      var rowsEnumerator = rowsToEvaluate.GetEnumerator();
218      var valuesEnumerator = (from xs in GetEstimatedValueVectors(ProblemData.Dataset, rowsToEvaluate)
219                              select AggregateEstimatedValues(xs))
220                             .GetEnumerator();
221
222      while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
223        evaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
224      }
225
226      return rows.Select(row => evaluationCache[row]);
227    }
228
229    public IEnumerable<IEnumerable<double>> GetEstimatedValueVectors(Dataset dataset, IEnumerable<int> rows) {
230      if (!Model.Models.Any()) yield break;
231      var estimatedValuesEnumerators = (from model in Model.Models
232                                        select model.GetEstimatedValues(dataset, rows).GetEnumerator())
233                                       .ToList();
234
235      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
236        yield return from enumerator in estimatedValuesEnumerators
237                     select enumerator.Current;
238      }
239    }
240
241    private double AggregateEstimatedValues(IEnumerable<double> estimatedValues) {
242      return estimatedValues.DefaultIfEmpty(double.NaN).Average();
243    }
244    #endregion
245
246    protected override void OnProblemDataChanged() {
247      trainingEvaluationCache.Clear();
248      testEvaluationCache.Clear();
249      evaluationCache.Clear();
250      IRegressionProblemData problemData = new RegressionProblemData(ProblemData.Dataset,
251                                                                     ProblemData.AllowedInputVariables,
252                                                                     ProblemData.TargetVariable);
253      problemData.TrainingPartition.Start = ProblemData.TrainingPartition.Start;
254      problemData.TrainingPartition.End = ProblemData.TrainingPartition.End;
255      problemData.TestPartition.Start = ProblemData.TestPartition.Start;
256      problemData.TestPartition.End = ProblemData.TestPartition.End;
257
258      foreach (var solution in RegressionSolutions) {
259        if (solution is RegressionEnsembleSolution)
260          solution.ProblemData = ProblemData;
261        else
262          solution.ProblemData = problemData;
263      }
264      foreach (var trainingPartition in trainingPartitions.Values) {
265        trainingPartition.Start = ProblemData.TrainingPartition.Start;
266        trainingPartition.End = ProblemData.TrainingPartition.End;
267      }
268      foreach (var testPartition in testPartitions.Values) {
269        testPartition.Start = ProblemData.TestPartition.Start;
270        testPartition.End = ProblemData.TestPartition.End;
271      }
272
273      base.OnProblemDataChanged();
274    }
275
276    public void AddRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
277      regressionSolutions.AddRange(solutions);
278
279      trainingEvaluationCache.Clear();
280      testEvaluationCache.Clear();
281      evaluationCache.Clear();
282    }
283    public void RemoveRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
284      regressionSolutions.RemoveRange(solutions);
285
286      trainingEvaluationCache.Clear();
287      testEvaluationCache.Clear();
288      evaluationCache.Clear();
289    }
290
291    private void regressionSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
292      foreach (var solution in e.Items) AddRegressionSolution(solution);
293      RecalculateResults();
294    }
295    private void regressionSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
296      foreach (var solution in e.Items) RemoveRegressionSolution(solution);
297      RecalculateResults();
298    }
299    private void regressionSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
300      foreach (var solution in e.OldItems) RemoveRegressionSolution(solution);
301      foreach (var solution in e.Items) AddRegressionSolution(solution);
302      RecalculateResults();
303    }
304
305    private void AddRegressionSolution(IRegressionSolution solution) {
306      if (Model.Models.Contains(solution.Model)) throw new ArgumentException();
307      Model.Add(solution.Model);
308      trainingPartitions[solution.Model] = solution.ProblemData.TrainingPartition;
309      testPartitions[solution.Model] = solution.ProblemData.TestPartition;
310
311      trainingEvaluationCache.Clear();
312      testEvaluationCache.Clear();
313      evaluationCache.Clear();
314    }
315
316    private void RemoveRegressionSolution(IRegressionSolution solution) {
317      if (!Model.Models.Contains(solution.Model)) throw new ArgumentException();
318      Model.Remove(solution.Model);
319      trainingPartitions.Remove(solution.Model);
320      testPartitions.Remove(solution.Model);
321
322      trainingEvaluationCache.Clear();
323      testEvaluationCache.Clear();
324      evaluationCache.Clear();
325    }
326  }
327}
Note: See TracBrowser for help on using the repository browser.