Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 18107 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 13.4 KB
RevLine 
[5816]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5816]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
[6588]22using System;
[5816]23using System.Collections.Generic;
24using System.Linq;
[6612]25using HeuristicLab.Collections;
[5816]26using HeuristicLab.Common;
27using HeuristicLab.Core;
[6588]28using HeuristicLab.Data;
[16565]29using HEAL.Attic;
[5816]30
31namespace HeuristicLab.Problems.DataAnalysis {
32  /// <summary>
33  /// Represents regression solutions that contain an ensemble of multiple regression models
34  /// </summary>
[16565]35  [StorableType("C5B38C31-4307-48E4-9BCD-6797C329E018")]
[5816]36  [Item("Regression Ensemble Solution", "A regression solution that contains an ensemble of multiple regression models")]
[12504]37  [Creatable(CreatableAttribute.Categories.DataAnalysisEnsembles, Priority = 100)]
[8724]38  public sealed class RegressionEnsembleSolution : RegressionSolutionBase, IRegressionEnsembleSolution {
[8167]39    private readonly Dictionary<int, double> trainingEvaluationCache = new Dictionary<int, double>();
40    private readonly Dictionary<int, double> testEvaluationCache = new Dictionary<int, double>();
[8724]41    private readonly Dictionary<int, double> evaluationCache = new Dictionary<int, double>();
[8151]42
[5816]43    public new IRegressionEnsembleModel Model {
44      get { return (IRegressionEnsembleModel)base.Model; }
45    }
46
[6666]47    public new RegressionEnsembleProblemData ProblemData {
48      get { return (RegressionEnsembleProblemData)base.ProblemData; }
49      set { base.ProblemData = value; }
50    }
51
[12816]52    [Storable]
[6612]53    private readonly ItemCollection<IRegressionSolution> regressionSolutions;
54    public IItemCollection<IRegressionSolution> RegressionSolutions {
55      get { return regressionSolutions; }
56    }
57
[5816]58    [Storable]
[8152]59    private readonly Dictionary<IRegressionModel, IntRange> trainingPartitions;
[5816]60    [Storable]
[8152]61    private readonly Dictionary<IRegressionModel, IntRange> testPartitions;
[5816]62
63    [StorableConstructor]
[16565]64    private RegressionEnsembleSolution(StorableConstructorFlag _) : base(_) {
[6612]65      regressionSolutions = new ItemCollection<IRegressionSolution>();
66    }
67    [StorableHook(HookType.AfterDeserialization)]
68    private void AfterDeserialization() {
[12816]69      if (!regressionSolutions.Any()) {
70        foreach (var model in Model.Models) {
71          IRegressionProblemData problemData = (IRegressionProblemData)ProblemData.Clone();
72          problemData.TrainingPartition.Start = trainingPartitions[model].Start;
73          problemData.TrainingPartition.End = trainingPartitions[model].End;
74          problemData.TestPartition.Start = testPartitions[model].Start;
75          problemData.TestPartition.End = testPartitions[model].End;
[6612]76
[12816]77          regressionSolutions.Add(model.CreateRegressionSolution(problemData));
78        }
[6612]79      }
[13704]80
81      RegisterModelEvents();
[6612]82      RegisterRegressionSolutionsEventHandler();
83    }
84
[6592]85    private RegressionEnsembleSolution(RegressionEnsembleSolution original, Cloner cloner)
[5816]86      : base(original, cloner) {
[6239]87      trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
88      testPartitions = new Dictionary<IRegressionModel, IntRange>();
[6302]89      foreach (var pair in original.trainingPartitions) {
90        trainingPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
[6239]91      }
[6302]92      foreach (var pair in original.testPartitions) {
93        testPartitions[cloner.Clone(pair.Key)] = cloner.Clone(pair.Value);
94      }
[6612]95
[13698]96      evaluationCache = new Dictionary<int, double>(original.ProblemData.Dataset.Rows);
[8174]97      trainingEvaluationCache = new Dictionary<int, double>(original.ProblemData.TrainingIndices.Count());
98      testEvaluationCache = new Dictionary<int, double>(original.ProblemData.TestIndices.Count());
99
[6612]100      regressionSolutions = cloner.Clone(original.regressionSolutions);
[13704]101      RegisterModelEvents();
[6612]102      RegisterRegressionSolutionsEventHandler();
[5816]103    }
[6239]104
[6666]105    public RegressionEnsembleSolution()
106      : base(new RegressionEnsembleModel(), RegressionEnsembleProblemData.EmptyProblemData) {
107      trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
108      testPartitions = new Dictionary<IRegressionModel, IntRange>();
109      regressionSolutions = new ItemCollection<IRegressionSolution>();
110
[13704]111      RegisterModelEvents();
[6666]112      RegisterRegressionSolutionsEventHandler();
113    }
114
[7738]115    public RegressionEnsembleSolution(IRegressionProblemData problemData)
[13698]116      : this(new RegressionEnsembleModel(), problemData) {
[7738]117    }
118
[13698]119    public RegressionEnsembleSolution(IRegressionEnsembleModel model, IRegressionProblemData problemData)
120      : base(model, new RegressionEnsembleProblemData(problemData)) {
121      trainingPartitions = new Dictionary<IRegressionModel, IntRange>();
122      testPartitions = new Dictionary<IRegressionModel, IntRange>();
123      regressionSolutions = new ItemCollection<IRegressionSolution>();
[5816]124
[13698]125      evaluationCache = new Dictionary<int, double>(problemData.Dataset.Rows);
[8174]126      trainingEvaluationCache = new Dictionary<int, double>(problemData.TrainingIndices.Count());
127      testEvaluationCache = new Dictionary<int, double>(problemData.TestIndices.Count());
128
[13702]129
130      var solutions = model.Models.Select(m => m.CreateRegressionSolution((IRegressionProblemData)problemData.Clone()));
131      foreach (var solution in solutions) {
132        regressionSolutions.Add(solution);
133        trainingPartitions.Add(solution.Model, solution.ProblemData.TrainingPartition);
134        testPartitions.Add(solution.Model, solution.ProblemData.TestPartition);
135      }
136
137      RecalculateResults();
[13704]138      RegisterModelEvents();
[6612]139      RegisterRegressionSolutionsEventHandler();
[5816]140    }
141
[13698]142
[5816]143    public override IDeepCloneable Clone(Cloner cloner) {
144      return new RegressionEnsembleSolution(this, cloner);
145    }
[13704]146
147    private void RegisterModelEvents() {
148      Model.Changed += Model_Changed;
149    }
[6612]150    private void RegisterRegressionSolutionsEventHandler() {
151      regressionSolutions.ItemsAdded += new CollectionItemsChangedEventHandler<IRegressionSolution>(regressionSolutions_ItemsAdded);
152      regressionSolutions.ItemsRemoved += new CollectionItemsChangedEventHandler<IRegressionSolution>(regressionSolutions_ItemsRemoved);
153      regressionSolutions.CollectionReset += new CollectionItemsChangedEventHandler<IRegressionSolution>(regressionSolutions_CollectionReset);
154    }
[5816]155
[6612]156    #region Evaluation
[8724]157    public override IEnumerable<double> EstimatedValues {
158      get { return GetEstimatedValues(Enumerable.Range(0, ProblemData.Dataset.Rows)); }
159    }
160
[5816]161    public override IEnumerable<double> EstimatedTrainingValues {
[8152]162      get {
163        var rows = ProblemData.TrainingIndices;
[8167]164        var rowsToEvaluate = rows.Except(trainingEvaluationCache.Keys);
[13704]165
[8152]166        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
[13697]167        var valuesEnumerator = Model.GetEstimatedValues(ProblemData.Dataset, rowsToEvaluate, (r, m) => RowIsTrainingForModel(r, m) && !RowIsTestForModel(r, m)).GetEnumerator();
[8152]168
169        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
[8167]170          trainingEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
[8152]171        }
172
[8167]173        return rows.Select(row => trainingEvaluationCache[row]);
[8152]174      }
[5816]175    }
176
177    public override IEnumerable<double> EstimatedTestValues {
[8152]178      get {
179        var rows = ProblemData.TestIndices;
[8167]180        var rowsToEvaluate = rows.Except(testEvaluationCache.Keys);
[8152]181        var rowsEnumerator = rowsToEvaluate.GetEnumerator();
[13697]182        var valuesEnumerator = Model.GetEstimatedValues(ProblemData.Dataset, rowsToEvaluate, RowIsTestForModel).GetEnumerator();
[8152]183
184        while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
[8167]185          testEvaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
[8152]186        }
187
[8167]188        return rows.Select(row => testEvaluationCache[row]);
[8152]189      }
[8151]190    }
[6254]191    private bool RowIsTrainingForModel(int currentRow, IRegressionModel model) {
192      return trainingPartitions == null || !trainingPartitions.ContainsKey(model) ||
193              (trainingPartitions[model].Start <= currentRow && currentRow < trainingPartitions[model].End);
194    }
195    private bool RowIsTestForModel(int currentRow, IRegressionModel model) {
196      return testPartitions == null || !testPartitions.ContainsKey(model) ||
197              (testPartitions[model].Start <= currentRow && currentRow < testPartitions[model].End);
198    }
199
[5816]200    public override IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows) {
[8167]201      var rowsToEvaluate = rows.Except(evaluationCache.Keys);
[8152]202      var rowsEnumerator = rowsToEvaluate.GetEnumerator();
[13697]203      var valuesEnumerator = Model.GetEstimatedValues(ProblemData.Dataset, rowsToEvaluate).GetEnumerator();
[8152]204
205      while (rowsEnumerator.MoveNext() & valuesEnumerator.MoveNext()) {
[8167]206        evaluationCache.Add(rowsEnumerator.Current, valuesEnumerator.Current);
[8152]207      }
208
[8167]209      return rows.Select(row => evaluationCache[row]);
[5816]210    }
211
[13697]212    public IEnumerable<IEnumerable<double>> GetEstimatedValueVectors(IEnumerable<int> rows) {
213      return Model.GetEstimatedValueVectors(ProblemData.Dataset, rows);
[5816]214    }
[6612]215    #endregion
[6520]216
[6666]217    protected override void OnProblemDataChanged() {
[8167]218      trainingEvaluationCache.Clear();
219      testEvaluationCache.Clear();
220      evaluationCache.Clear();
[6666]221      IRegressionProblemData problemData = new RegressionProblemData(ProblemData.Dataset,
222                                                                     ProblemData.AllowedInputVariables,
223                                                                     ProblemData.TargetVariable);
224      problemData.TrainingPartition.Start = ProblemData.TrainingPartition.Start;
225      problemData.TrainingPartition.End = ProblemData.TrainingPartition.End;
226      problemData.TestPartition.Start = ProblemData.TestPartition.Start;
227      problemData.TestPartition.End = ProblemData.TestPartition.End;
228
229      foreach (var solution in RegressionSolutions) {
230        if (solution is RegressionEnsembleSolution)
231          solution.ProblemData = ProblemData;
232        else
233          solution.ProblemData = problemData;
234      }
235      foreach (var trainingPartition in trainingPartitions.Values) {
236        trainingPartition.Start = ProblemData.TrainingPartition.Start;
237        trainingPartition.End = ProblemData.TrainingPartition.End;
238      }
239      foreach (var testPartition in testPartitions.Values) {
240        testPartition.Start = ProblemData.TestPartition.Start;
241        testPartition.End = ProblemData.TestPartition.End;
242      }
243
244      base.OnProblemDataChanged();
245    }
246
[13704]247    private void Model_Changed(object sender, EventArgs e) {
248      var modelSet = new HashSet<IRegressionModel>(Model.Models);
249      foreach (var model in Model.Models) {
250        if (!trainingPartitions.ContainsKey(model)) trainingPartitions.Add(model, ProblemData.TrainingPartition);
251        if (!testPartitions.ContainsKey(model)) testPartitions.Add(model, ProblemData.TrainingPartition);
252      }
253      foreach (var model in trainingPartitions.Keys) {
254        if (modelSet.Contains(model)) continue;
255        trainingPartitions.Remove(model);
256        testPartitions.Remove(model);
257      }
[8152]258
[8167]259      trainingEvaluationCache.Clear();
260      testEvaluationCache.Clear();
261      evaluationCache.Clear();
[13704]262
263      OnModelChanged();
[6612]264    }
[13704]265
266    public void AddRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
267      regressionSolutions.AddRange(solutions);
268    }
[6612]269    public void RemoveRegressionSolutions(IEnumerable<IRegressionSolution> solutions) {
270      regressionSolutions.RemoveRange(solutions);
271    }
[6520]272
[6612]273    private void regressionSolutions_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
[13704]274      foreach (var solution in e.Items) {
275        trainingPartitions.Add(solution.Model, solution.ProblemData.TrainingPartition);
276        testPartitions.Add(solution.Model, solution.ProblemData.TestPartition);
277      }
278      Model.AddRange(e.Items.Select(s => s.Model));
[6520]279    }
[6612]280    private void regressionSolutions_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
[13704]281      foreach (var solution in e.Items) {
282        trainingPartitions.Remove(solution.Model);
283        testPartitions.Remove(solution.Model);
284      }
285      Model.RemoveRange(e.Items.Select(s => s.Model));
[6612]286    }
287    private void regressionSolutions_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRegressionSolution> e) {
[13704]288      foreach (var solution in e.OldItems) {
289        trainingPartitions.Remove(solution.Model);
290        testPartitions.Remove(solution.Model);
291      }
292      Model.RemoveRange(e.OldItems.Select(s => s.Model));
[6520]293
[13704]294      foreach (var solution in e.Items) {
295        trainingPartitions.Add(solution.Model, solution.ProblemData.TrainingPartition);
296        testPartitions.Add(solution.Model, solution.ProblemData.TestPartition);
297      }
298      Model.AddRange(e.Items.Select(s => s.Model));
[6612]299    }
[5816]300  }
301}
Note: See TracBrowser for help on using the repository browser.