Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionEnsembleSolution.cs @ 8508

Last change on this file since 8508 was 8508, checked in by sforsten, 12 years ago

#1776: merged r7864:8507 trunk into branch

File size: 15.4 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    protected override void RecalculateResults() {
158      CalculateResults();
159    }
160
161    #region Evaluation
162    public override IEnumerable<double> EstimatedTrainingValues {
163      get {
164        var rows = ProblemData.TrainingIndices;
165        var rowsToEvaluate = rows.Except(trainingEvaluationCache.Keys);
166        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
167        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, (r, m) => RowIsTrainingForModel(r, m) && !RowIsTestForModel(r, m)).GetEnumerator();
168
169        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
170          trainingEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
171        }
172
173        return rows.Select(row => trainingEvaluationCache[row]);
174      }
175    }
176
177    public override IEnumerable<double> EstimatedTestValues {
178      get {
179        var rows = ProblemData.TestIndices;
180        var rowsToEvaluate = rows.Except(testEvaluationCache.Keys);
181        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
182        var valuesEnumerator = GetEstimatedValues(rowsToEvaluate, RowIsTestForModel).GetEnumerator();
183
184        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
185          testEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
186        }
187
188        return rows.Select(row => testEvaluationCache[row]);
189      }
190    }
191
192    private IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows, Func<int, IRegressionModel, bool> modelSelectionPredicate) {
193      var estimatedValuesEnumerators = (from model in Model.Models
194                                        select new { Model = model, EstimatedValuesEnumerator = model.GetEstimatedValues(ProblemData.Dataset, rows).GetEnumerator() })
195                                       .ToList();
196      var rowsEnumerator = rows.GetEnumerator();
197      // aggregate to make sure that MoveNext is called for all enumerators
198      while (rowsEnumerator.MoveNext() & estimatedValuesEnumerators.Select(en => en.EstimatedValuesEnumerator.MoveNext()).Aggregate(true, (acc, b) => acc & b)) {
199        int currentRow = rowsEnumerator.Current;
200
201        var selectedEnumerators = from pair in estimatedValuesEnumerators
202                                  where modelSelectionPredicate(currentRow, pair.Model)
203                                  select pair.EstimatedValuesEnumerator;
204
205        yield return AggregateEstimatedValues(selectedEnumerators.Select(x => x.Current));
206      }
207    }
208
209    private bool RowIsTrainingForModel(int currentRow, IRegressionModel model) {
210      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
211              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
212    }
213
214    private bool RowIsTestForModel(int currentRow, IRegressionModel model) {
215      return testPartitions == null || !testPartitions.ContainsKey(model) ||
216              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
217    }
218
219    public override IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows) {
220      var rowsToEvaluate = rows.Except(evaluationCache.Keys);
221      var rowsEnumerator = rowsToEvaluate.GetEnumerator();
222      var valuesEnumerator = (from xs in GetEstimatedValueVectors(ProblemData.Dataset, rowsToEvaluate)
223                              select AggregateEstimatedValues(xs))
224                             .GetEnumerator();
225
226      while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
227        evaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
228      }
229
230      return rows.Select(row => evaluationCache[row]);
231    }
232
233    public IEnumerable<IEnumerable<double>> GetEstimatedValueVectors(Dataset dataset, IEnumerable<int> rows) {
234      if (!Model.Models.Any()) yield break;
235      var estimatedValuesEnumerators = (from model in Model.Models
236                                        select model.GetEstimatedValues(dataset, rows).GetEnumerator())
237                                       .ToList();
238
239      while (estimatedValuesEnumerators.All(en => en.MoveNext())) {
240        yield return from enumerator in estimatedValuesEnumerators
241                     select enumerator.Current;
242      }
243    }
244
245    private double AggregateEstimatedValues(IEnumerable<double> estimatedValues) {
246      return estimatedValues.DefaultIfEmpty(double.NaN).Average();
247    }
248    #endregion
249
250    protected override void OnProblemDataChanged() {
251      trainingEvaluationCache.Clear();
252      testEvaluationCache.Clear();
253      evaluationCache.Clear();
254      IRegressionProblemData problemData = new RegressionProblemData(ProblemData.Dataset,
255                                                                     ProblemData.AllowedInputVariables,
256                                                                     ProblemData.TargetVariable);
257      problemData.TrainingPartition.Start = ProblemData.TrainingPartition.Start;
258      problemData.TrainingPartition.End = ProblemData.TrainingPartition.End;
259      problemData.TestPartition.Start = ProblemData.TestPartition.Start;
260      problemData.TestPartition.End = ProblemData.TestPartition.End;
261
262      foreach (var solution in RegressionSolutions) {
263        if (solution is RegressionEnsembleSolution)
264          solution.ProblemData = ProblemData;
265        else
266          solution.ProblemData = problemData;
267      }
268      foreach (var trainingPartition in trainingPartitions.Values) {
269        trainingPartition.Start = ProblemData.TrainingPartition.Start;
270        trainingPartition.End = ProblemData.TrainingPartition.End;
271      }
272      foreach (var testPartition in testPartitions.Values) {
273        testPartition.Start = ProblemData.TestPartition.Start;
274        testPartition.End = ProblemData.TestPartition.End;
275      }
276
277      base.OnProblemDataChanged();
278    }
279
280    public void AddRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
281      regressionSolutions.AddRange(solutions);
282
283      trainingEvaluationCache.Clear();
284      testEvaluationCache.Clear();
285      evaluationCache.Clear();
286    }
287    public void RemoveRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
288      regressionSolutions.RemoveRange(solutions);
289
290      trainingEvaluationCache.Clear();
291      testEvaluationCache.Clear();
292      evaluationCache.Clear();
293    }
294
295    private void regressionSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
296      foreach (var solution in e.Items) AddRegressionSolution(solution);
297      RecalculateResults();
298    }
299    private void regressionSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
300      foreach (var solution in e.Items) RemoveRegressionSolution(solution);
301      RecalculateResults();
302    }
303    private void regressionSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
304      foreach (var solution in e.OldItems) RemoveRegressionSolution(solution);
305      foreach (var solution in e.Items) AddRegressionSolution(solution);
306      RecalculateResults();
307    }
308
309    private void AddRegressionSolution(IRegressionSolution solution) {
310      if (Model.Models.Contains(solution.Model)) throw new ArgumentException();
311      Model.Add(solution.Model);
312      trainingPartitions[solution.Model] = solution.ProblemData.TrainingPartition;
313      testPartitions[solution.Model] = solution.ProblemData.TestPartition;
314
315      trainingEvaluationCache.Clear();
316      testEvaluationCache.Clear();
317      evaluationCache.Clear();
318    }
319
320    private void RemoveRegressionSolution(IRegressionSolution solution) {
321      if (!Model.Models.Contains(solution.Model)) throw new ArgumentException();
322      Model.Remove(solution.Model);
323      trainingPartitions.Remove(solution.Model);
324      testPartitions.Remove(solution.Model);
325
326      trainingEvaluationCache.Clear();
327      testEvaluationCache.Clear();
328      evaluationCache.Clear();
329    }
330  }
331}
Note: See TracBrowser for help on using the repository browser.