Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionEnsembleSolution.cs @ 8206

Last change on this file since 8206 was 8206, checked in by gkronber, 12 years ago

#1847: merged r8084:8205 from trunk into GP move operators branch

File size: 15.6 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 trimean
247      var orderdValues = estimatedValues
248        .Where(x => !double.IsNaN(x))
249        .DefaultIfEmpty(0.0)
250        .OrderBy(x => x)
251        .ToArray();
252      return (orderdValues[(int)Math.Floor(orderdValues.Length * 0.25)] +
253              orderdValues[(int)Math.Floor(orderdValues.Length * 0.75)]) / 2.0;
254    }
255    #endregion
256
257    protected override void OnProblemDataChanged() {
258      trainingEvaluationCache.Clear();
259      testEvaluationCache.Clear();
260      evaluationCache.Clear();
261      IRegressionProblemData problemData = new RegressionProblemData(ProblemData.Dataset,
262                                                                     ProblemData.AllowedInputVariables,
263                                                                     ProblemData.TargetVariable);
264      problemData.TrainingPartition.Start = ProblemData.TrainingPartition.Start;
265      problemData.TrainingPartition.End = ProblemData.TrainingPartition.End;
266      problemData.TestPartition.Start = ProblemData.TestPartition.Start;
267      problemData.TestPartition.End = ProblemData.TestPartition.End;
268
269      foreach (var solution in RegressionSolutions) {
270        if (solution is RegressionEnsembleSolution)
271          solution.ProblemData = ProblemData;
272        else
273          solution.ProblemData = problemData;
274      }
275      foreach (var trainingPartition in trainingPartitions.Values) {
276        trainingPartition.Start = ProblemData.TrainingPartition.Start;
277        trainingPartition.End = ProblemData.TrainingPartition.End;
278      }
279      foreach (var testPartition in testPartitions.Values) {
280        testPartition.Start = ProblemData.TestPartition.Start;
281        testPartition.End = ProblemData.TestPartition.End;
282      }
283
284      base.OnProblemDataChanged();
285    }
286
287    public void AddRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
288      regressionSolutions.AddRange(solutions);
289
290      trainingEvaluationCache.Clear();
291      testEvaluationCache.Clear();
292      evaluationCache.Clear();
293    }
294    public void RemoveRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
295      regressionSolutions.RemoveRange(solutions);
296
297      trainingEvaluationCache.Clear();
298      testEvaluationCache.Clear();
299      evaluationCache.Clear();
300    }
301
302    private void regressionSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
303      foreach (var solution in e.Items) AddRegressionSolution(solution);
304      RecalculateResults();
305    }
306    private void regressionSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
307      foreach (var solution in e.Items) RemoveRegressionSolution(solution);
308      RecalculateResults();
309    }
310    private void regressionSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
311      foreach (var solution in e.OldItems) RemoveRegressionSolution(solution);
312      foreach (var solution in e.Items) AddRegressionSolution(solution);
313      RecalculateResults();
314    }
315
316    private void AddRegressionSolution(IRegressionSolution solution) {
317      if (Model.Models.Contains(solution.Model)) throw new ArgumentException();
318      Model.Add(solution.Model);
319      trainingPartitions[solution.Model] = solution.ProblemData.TrainingPartition;
320      testPartitions[solution.Model] = solution.ProblemData.TestPartition;
321
322      trainingEvaluationCache.Clear();
323      testEvaluationCache.Clear();
324      evaluationCache.Clear();
325    }
326
327    private void RemoveRegressionSolution(IRegressionSolution solution) {
328      if (!Model.Models.Contains(solution.Model)) throw new ArgumentException();
329      Model.Remove(solution.Model);
330      trainingPartitions.Remove(solution.Model);
331      testPartitions.Remove(solution.Model);
332
333      trainingEvaluationCache.Clear();
334      testEvaluationCache.Clear();
335      evaluationCache.Clear();
336    }
337  }
338}
Note: See TracBrowser for help on using the repository browser.