1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2015 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Drawing;
|
---|
25 | using System.Linq;
|
---|
26 | using System.Threading;
|
---|
27 | using System.Threading.Tasks;
|
---|
28 | using HeuristicLab.Collections;
|
---|
29 | using HeuristicLab.Common;
|
---|
30 | using HeuristicLab.Core;
|
---|
31 | using HeuristicLab.Data;
|
---|
32 | using HeuristicLab.Optimization;
|
---|
33 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
34 | using HeuristicLab.Problems.DataAnalysis;
|
---|
35 | using HeuristicLab.Problems.DataAnalysis.Symbolic;
|
---|
36 |
|
---|
37 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
38 | [Item("Cross Validation (CV)", "Cross-validation wrapper for data analysis algorithms.")]
|
---|
39 | [Creatable(CreatableAttribute.Categories.DataAnalysis, Priority = 100)]
|
---|
40 | [StorableClass]
|
---|
41 | public sealed class CrossValidation : ParameterizedNamedItem, IAlgorithm, IStorableContent {
|
---|
42 | private readonly ManualResetEvent signaler = new ManualResetEvent(true);
|
---|
43 | private CancellationToken cancellationToken;
|
---|
44 |
|
---|
45 | public CrossValidation()
|
---|
46 | : base() {
|
---|
47 | name = ItemName;
|
---|
48 | description = ItemDescription;
|
---|
49 |
|
---|
50 | executionState = ExecutionState.Stopped;
|
---|
51 | runs = new RunCollection { OptimizerName = name };
|
---|
52 | runsCounter = 0;
|
---|
53 |
|
---|
54 | algorithm = null;
|
---|
55 | clonedAlgorithms = new ItemCollection<IAlgorithm>();
|
---|
56 | results = new ResultCollection();
|
---|
57 |
|
---|
58 | folds = new IntValue(2);
|
---|
59 | numberOfWorkers = new IntValue(1);
|
---|
60 | samplesStart = new IntValue(0);
|
---|
61 | samplesEnd = new IntValue(0);
|
---|
62 | storeAlgorithmInEachRun = false;
|
---|
63 |
|
---|
64 | RegisterEvents();
|
---|
65 | if (Algorithm != null) RegisterAlgorithmEvents();
|
---|
66 | }
|
---|
67 |
|
---|
68 | public string Filename { get; set; }
|
---|
69 |
|
---|
70 | #region persistence and cloning
|
---|
71 | [StorableConstructor]
|
---|
72 | private CrossValidation(bool deserializing)
|
---|
73 | : base(deserializing) {
|
---|
74 | }
|
---|
75 | [StorableHook(HookType.AfterDeserialization)]
|
---|
76 | private void AfterDeserialization() {
|
---|
77 | RegisterEvents();
|
---|
78 | if (Algorithm != null) RegisterAlgorithmEvents();
|
---|
79 | }
|
---|
80 |
|
---|
81 | private CrossValidation(CrossValidation original, Cloner cloner)
|
---|
82 | : base(original, cloner) {
|
---|
83 | executionState = original.executionState;
|
---|
84 | storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
|
---|
85 | runs = cloner.Clone(original.runs);
|
---|
86 | runsCounter = original.runsCounter;
|
---|
87 | algorithm = cloner.Clone(original.algorithm);
|
---|
88 | clonedAlgorithms = cloner.Clone(original.clonedAlgorithms);
|
---|
89 | results = cloner.Clone(original.results);
|
---|
90 |
|
---|
91 | folds = cloner.Clone(original.folds);
|
---|
92 | numberOfWorkers = cloner.Clone(original.numberOfWorkers);
|
---|
93 | samplesStart = cloner.Clone(original.samplesStart);
|
---|
94 | samplesEnd = cloner.Clone(original.samplesEnd);
|
---|
95 | RegisterEvents();
|
---|
96 | if (Algorithm != null) RegisterAlgorithmEvents();
|
---|
97 | }
|
---|
98 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
99 | return new CrossValidation(this, cloner);
|
---|
100 | }
|
---|
101 |
|
---|
102 | #endregion
|
---|
103 |
|
---|
104 | #region properties
|
---|
105 | [Storable]
|
---|
106 | private IAlgorithm algorithm;
|
---|
107 | public IAlgorithm Algorithm {
|
---|
108 | get { return algorithm; }
|
---|
109 | set {
|
---|
110 | if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
|
---|
111 | throw new InvalidOperationException("Changing the algorithm is only allowed if the CrossValidation is stopped or prepared.");
|
---|
112 | if (algorithm != value) {
|
---|
113 | if (value != null && value.Problem != null && !(value.Problem is IDataAnalysisProblem))
|
---|
114 | throw new ArgumentException("Only algorithms with a DataAnalysisProblem could be used for the cross validation.");
|
---|
115 | if (algorithm != null) DeregisterAlgorithmEvents();
|
---|
116 | algorithm = value;
|
---|
117 | Parameters.Clear();
|
---|
118 |
|
---|
119 | if (algorithm != null) {
|
---|
120 | algorithm.StoreAlgorithmInEachRun = false;
|
---|
121 | RegisterAlgorithmEvents();
|
---|
122 | algorithm.Prepare(true);
|
---|
123 | Parameters.AddRange(algorithm.Parameters);
|
---|
124 | }
|
---|
125 | OnAlgorithmChanged();
|
---|
126 | Prepare();
|
---|
127 | }
|
---|
128 | }
|
---|
129 | }
|
---|
130 |
|
---|
131 |
|
---|
132 | [Storable]
|
---|
133 | private IDataAnalysisProblem problem;
|
---|
134 | public IDataAnalysisProblem Problem {
|
---|
135 | get {
|
---|
136 | if (algorithm == null)
|
---|
137 | return null;
|
---|
138 | return (IDataAnalysisProblem)algorithm.Problem;
|
---|
139 | }
|
---|
140 | set {
|
---|
141 | if (ExecutionState != ExecutionState.Prepared && ExecutionState != ExecutionState.Stopped)
|
---|
142 | throw new InvalidOperationException("Changing the problem is only allowed if the CrossValidation is stopped or prepared.");
|
---|
143 | if (algorithm == null) throw new ArgumentNullException("Could not set a problem before an algorithm was set.");
|
---|
144 | algorithm.Problem = value;
|
---|
145 | problem = value;
|
---|
146 | }
|
---|
147 | }
|
---|
148 |
|
---|
149 | IProblem IAlgorithm.Problem {
|
---|
150 | get { return Problem; }
|
---|
151 | set {
|
---|
152 | if (value != null && !ProblemType.IsInstanceOfType(value))
|
---|
153 | throw new ArgumentException("Only DataAnalysisProblems could be used for the cross validation.");
|
---|
154 | Problem = (IDataAnalysisProblem)value;
|
---|
155 | }
|
---|
156 | }
|
---|
157 | public Type ProblemType {
|
---|
158 | get { return typeof(IDataAnalysisProblem); }
|
---|
159 | }
|
---|
160 |
|
---|
161 | [Storable]
|
---|
162 | private ItemCollection<IAlgorithm> clonedAlgorithms;
|
---|
163 |
|
---|
164 | public IEnumerable<IOptimizer> NestedOptimizers {
|
---|
165 | get {
|
---|
166 | if (Algorithm == null) yield break;
|
---|
167 | yield return Algorithm;
|
---|
168 | }
|
---|
169 | }
|
---|
170 |
|
---|
171 | [Storable]
|
---|
172 | private ResultCollection results;
|
---|
173 | public ResultCollection Results {
|
---|
174 | get { return results; }
|
---|
175 | }
|
---|
176 |
|
---|
177 | [Storable]
|
---|
178 | private IntValue folds;
|
---|
179 | public IntValue Folds {
|
---|
180 | get { return folds; }
|
---|
181 | }
|
---|
182 | [Storable]
|
---|
183 | private IntValue samplesStart;
|
---|
184 | public IntValue SamplesStart {
|
---|
185 | get { return samplesStart; }
|
---|
186 | }
|
---|
187 | [Storable]
|
---|
188 | private IntValue samplesEnd;
|
---|
189 | public IntValue SamplesEnd {
|
---|
190 | get { return samplesEnd; }
|
---|
191 | }
|
---|
192 | [Storable]
|
---|
193 | private IntValue numberOfWorkers;
|
---|
194 | public IntValue NumberOfWorkers {
|
---|
195 | get { return numberOfWorkers; }
|
---|
196 | }
|
---|
197 |
|
---|
198 | [Storable]
|
---|
199 | private bool storeAlgorithmInEachRun;
|
---|
200 | public bool StoreAlgorithmInEachRun {
|
---|
201 | get { return storeAlgorithmInEachRun; }
|
---|
202 | set {
|
---|
203 | if (storeAlgorithmInEachRun != value) {
|
---|
204 | storeAlgorithmInEachRun = value;
|
---|
205 | OnStoreAlgorithmInEachRunChanged();
|
---|
206 | }
|
---|
207 | }
|
---|
208 | }
|
---|
209 |
|
---|
210 | [Storable]
|
---|
211 | private int runsCounter;
|
---|
212 | [Storable]
|
---|
213 | private RunCollection runs;
|
---|
214 | public RunCollection Runs {
|
---|
215 | get { return runs; }
|
---|
216 | }
|
---|
217 |
|
---|
218 | [Storable]
|
---|
219 | private ExecutionState executionState;
|
---|
220 | public ExecutionState ExecutionState {
|
---|
221 | get { return executionState; }
|
---|
222 | private set {
|
---|
223 | if (executionState != value) {
|
---|
224 | executionState = value;
|
---|
225 | OnExecutionStateChanged();
|
---|
226 | OnItemImageChanged();
|
---|
227 | }
|
---|
228 | }
|
---|
229 | }
|
---|
230 | public static new Image StaticItemImage {
|
---|
231 | get { return HeuristicLab.Common.Resources.VSImageLibrary.Event; }
|
---|
232 | }
|
---|
233 | public override Image ItemImage {
|
---|
234 | get {
|
---|
235 | if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
|
---|
236 | else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
|
---|
237 | else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
|
---|
238 | else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
|
---|
239 | else return base.ItemImage;
|
---|
240 | }
|
---|
241 | }
|
---|
242 |
|
---|
243 | public TimeSpan ExecutionTime {
|
---|
244 | get {
|
---|
245 | if (ExecutionState != ExecutionState.Prepared)
|
---|
246 | return TimeSpan.FromMilliseconds(clonedAlgorithms.Select(x => x.ExecutionTime.TotalMilliseconds).Sum());
|
---|
247 | return TimeSpan.Zero;
|
---|
248 | }
|
---|
249 | }
|
---|
250 | #endregion
|
---|
251 |
|
---|
252 | protected override void OnNameChanged() {
|
---|
253 | base.OnNameChanged();
|
---|
254 | Runs.OptimizerName = Name;
|
---|
255 | }
|
---|
256 |
|
---|
257 | public void Prepare() {
|
---|
258 | if (ExecutionState == ExecutionState.Started)
|
---|
259 | throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
|
---|
260 | results.Clear();
|
---|
261 | clonedAlgorithms.Clear();
|
---|
262 | if (Algorithm != null) {
|
---|
263 | Algorithm.Prepare();
|
---|
264 | if (Algorithm.ExecutionState == ExecutionState.Prepared) OnPrepared();
|
---|
265 | }
|
---|
266 | }
|
---|
267 | public void Prepare(bool clearRuns) {
|
---|
268 | if (clearRuns) runs.Clear();
|
---|
269 | Prepare();
|
---|
270 | }
|
---|
271 | public void Start() {
|
---|
272 | StartAsync().Wait();
|
---|
273 | }
|
---|
274 | public async Task StartAsync() {
|
---|
275 | await StartAsync(CancellationToken.None);
|
---|
276 | }
|
---|
277 | public async Task StartAsync(CancellationToken cancellationToken) {
|
---|
278 | this.cancellationToken = cancellationToken;
|
---|
279 | signaler.Reset();
|
---|
280 | await Task.Run(() => {
|
---|
281 | if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
|
---|
282 | throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
|
---|
283 |
|
---|
284 | if (Algorithm != null) {
|
---|
285 | //create cloned algorithms
|
---|
286 | if (clonedAlgorithms.Count == 0) {
|
---|
287 | int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
|
---|
288 |
|
---|
289 | for (int i = 0; i < Folds.Value; i++) {
|
---|
290 | IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
|
---|
291 | clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
|
---|
292 | IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
|
---|
293 | ISymbolicDataAnalysisProblem symbolicProblem = problem as ISymbolicDataAnalysisProblem;
|
---|
294 |
|
---|
295 | int testStart = (i * testSamplesCount) + SamplesStart.Value;
|
---|
296 | int testEnd = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
|
---|
297 |
|
---|
298 | problem.ProblemData.TrainingPartition.Start = SamplesStart.Value;
|
---|
299 | problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
|
---|
300 | problem.ProblemData.TestPartition.Start = testStart;
|
---|
301 | problem.ProblemData.TestPartition.End = testEnd;
|
---|
302 | DataAnalysisProblemData problemData = problem.ProblemData as DataAnalysisProblemData;
|
---|
303 | if (problemData != null) {
|
---|
304 | problemData.TrainingPartitionParameter.Hidden = false;
|
---|
305 | problemData.TestPartitionParameter.Hidden = false;
|
---|
306 | }
|
---|
307 |
|
---|
308 | if (symbolicProblem != null) {
|
---|
309 | symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
|
---|
310 | symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
|
---|
311 | }
|
---|
312 | clonedAlgorithm.Prepare();
|
---|
313 | clonedAlgorithms.Add(clonedAlgorithm);
|
---|
314 | }
|
---|
315 | }
|
---|
316 |
|
---|
317 | //start prepared or paused cloned algorithms
|
---|
318 | int startedAlgorithms = 0;
|
---|
319 | foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
|
---|
320 | if (startedAlgorithms < NumberOfWorkers.Value) {
|
---|
321 | if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
|
---|
322 | clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
|
---|
323 |
|
---|
324 | // start and wait until the alg is started
|
---|
325 | using (var signal = new ManualResetEvent(false)) {
|
---|
326 | EventHandler signalSetter = (sender, args) => { signal.Set(); };
|
---|
327 | clonedAlgorithm.Started += signalSetter;
|
---|
328 | clonedAlgorithm.StartAsync(cancellationToken);
|
---|
329 | signal.WaitOne();
|
---|
330 | clonedAlgorithm.Started -= signalSetter;
|
---|
331 |
|
---|
332 | startedAlgorithms++;
|
---|
333 | }
|
---|
334 | }
|
---|
335 | }
|
---|
336 | }
|
---|
337 | OnStarted();
|
---|
338 | }
|
---|
339 | }, cancellationToken);
|
---|
340 | }
|
---|
341 |
|
---|
342 | private bool pausePending;
|
---|
343 | public void Pause() {
|
---|
344 | if (ExecutionState != ExecutionState.Started)
|
---|
345 | throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
|
---|
346 | if (!pausePending) {
|
---|
347 | pausePending = true;
|
---|
348 | PauseAllClonedAlgorithms();
|
---|
349 | }
|
---|
350 | }
|
---|
351 | private void PauseAllClonedAlgorithms() {
|
---|
352 | foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
|
---|
353 | if (clonedAlgorithm.ExecutionState == ExecutionState.Started)
|
---|
354 | clonedAlgorithm.Pause();
|
---|
355 | }
|
---|
356 | }
|
---|
357 |
|
---|
358 | private bool stopPending;
|
---|
359 | public void Stop() {
|
---|
360 | if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
|
---|
361 | throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".",
|
---|
362 | ExecutionState));
|
---|
363 | if (!stopPending) {
|
---|
364 | stopPending = true;
|
---|
365 | StopAllClonedAlgorithms();
|
---|
366 | }
|
---|
367 | }
|
---|
368 | private void StopAllClonedAlgorithms() {
|
---|
369 | foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
|
---|
370 | if (clonedAlgorithm.ExecutionState == ExecutionState.Started ||
|
---|
371 | clonedAlgorithm.ExecutionState == ExecutionState.Paused)
|
---|
372 | clonedAlgorithm.Stop();
|
---|
373 | }
|
---|
374 | }
|
---|
375 |
|
---|
376 | #region collect parameters and results
|
---|
377 | public override void CollectParameterValues(IDictionary<string, IItem> values) {
|
---|
378 | values.Add("Algorithm Name", new StringValue(Name));
|
---|
379 | values.Add("Algorithm Type", new StringValue(GetType().GetPrettyName()));
|
---|
380 | values.Add("Folds", new IntValue(Folds.Value));
|
---|
381 |
|
---|
382 | if (algorithm != null) {
|
---|
383 | values.Add("CrossValidation Algorithm Name", new StringValue(Algorithm.Name));
|
---|
384 | values.Add("CrossValidation Algorithm Type", new StringValue(Algorithm.GetType().GetPrettyName()));
|
---|
385 | base.CollectParameterValues(values);
|
---|
386 | }
|
---|
387 | if (Problem != null) {
|
---|
388 | values.Add("Problem Name", new StringValue(Problem.Name));
|
---|
389 | values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
|
---|
390 | Problem.CollectParameterValues(values);
|
---|
391 | }
|
---|
392 | }
|
---|
393 |
|
---|
394 | public void CollectResultValues(IDictionary<string, IItem> results) {
|
---|
395 | var clonedResults = (ResultCollection)this.results.Clone();
|
---|
396 | foreach (var result in clonedResults) {
|
---|
397 | results.Add(result.Name, result.Value);
|
---|
398 | }
|
---|
399 | }
|
---|
400 |
|
---|
401 | private void AggregateResultValues(IDictionary<string, IItem> results) {
|
---|
402 | IEnumerable<IRun> runs = clonedAlgorithms.Select(alg => alg.Runs.FirstOrDefault()).Where(run => run != null);
|
---|
403 | IEnumerable<KeyValuePair<string, IItem>> resultCollections = runs.Where(x => x != null).SelectMany(x => x.Results).ToList();
|
---|
404 |
|
---|
405 | foreach (IResult result in ExtractAndAggregateResults<IntValue>(resultCollections))
|
---|
406 | results.Add(result.Name, result.Value);
|
---|
407 | foreach (IResult result in ExtractAndAggregateResults<DoubleValue>(resultCollections))
|
---|
408 | results.Add(result.Name, result.Value);
|
---|
409 | foreach (IResult result in ExtractAndAggregateResults<PercentValue>(resultCollections))
|
---|
410 | results.Add(result.Name, result.Value);
|
---|
411 | foreach (IResult result in ExtractAndAggregateRegressionSolutions(resultCollections)) {
|
---|
412 | results.Add(result.Name, result.Value);
|
---|
413 | }
|
---|
414 | foreach (IResult result in ExtractAndAggregateClassificationSolutions(resultCollections)) {
|
---|
415 | results.Add(result.Name, result.Value);
|
---|
416 | }
|
---|
417 | results.Add("Execution Time", new TimeSpanValue(this.ExecutionTime));
|
---|
418 | results.Add("CrossValidation Folds", new RunCollection(runs));
|
---|
419 | }
|
---|
420 |
|
---|
421 | private IEnumerable<IResult> ExtractAndAggregateRegressionSolutions(IEnumerable<KeyValuePair<string, IItem>> resultCollections) {
|
---|
422 | Dictionary<string, List<IRegressionSolution>> resultSolutions = new Dictionary<string, List<IRegressionSolution>>();
|
---|
423 | foreach (var result in resultCollections) {
|
---|
424 | var regressionSolution = result.Value as IRegressionSolution;
|
---|
425 | if (regressionSolution != null) {
|
---|
426 | if (resultSolutions.ContainsKey(result.Key)) {
|
---|
427 | resultSolutions[result.Key].Add(regressionSolution);
|
---|
428 | } else {
|
---|
429 | resultSolutions.Add(result.Key, new List<IRegressionSolution>() { regressionSolution });
|
---|
430 | }
|
---|
431 | }
|
---|
432 | }
|
---|
433 | List<IResult> aggregatedResults = new List<IResult>();
|
---|
434 | foreach (KeyValuePair<string, List<IRegressionSolution>> solutions in resultSolutions) {
|
---|
435 | // clone manually to correctly clone references between cloned root objects
|
---|
436 | Cloner cloner = new Cloner();
|
---|
437 | var problemDataClone = (IRegressionProblemData)cloner.Clone(Problem.ProblemData);
|
---|
438 | // set partitions of problem data clone correctly
|
---|
439 | problemDataClone.TrainingPartition.Start = SamplesStart.Value; problemDataClone.TrainingPartition.End = SamplesEnd.Value;
|
---|
440 | problemDataClone.TestPartition.Start = SamplesStart.Value; problemDataClone.TestPartition.End = SamplesEnd.Value;
|
---|
441 | // clone models
|
---|
442 | var ensembleSolution = new RegressionEnsembleSolution(problemDataClone);
|
---|
443 | ensembleSolution.AddRegressionSolutions(solutions.Value);
|
---|
444 |
|
---|
445 | aggregatedResults.Add(new Result(solutions.Key + " (ensemble)", ensembleSolution));
|
---|
446 | }
|
---|
447 | List<IResult> flattenedResults = new List<IResult>();
|
---|
448 | CollectResultsRecursively("", aggregatedResults, flattenedResults);
|
---|
449 | return flattenedResults;
|
---|
450 | }
|
---|
451 |
|
---|
452 | private IEnumerable<IResult> ExtractAndAggregateClassificationSolutions(IEnumerable<KeyValuePair<string, IItem>> resultCollections) {
|
---|
453 | Dictionary<string, List<IClassificationSolution>> resultSolutions = new Dictionary<string, List<IClassificationSolution>>();
|
---|
454 | foreach (var result in resultCollections) {
|
---|
455 | var classificationSolution = result.Value as IClassificationSolution;
|
---|
456 | if (classificationSolution != null) {
|
---|
457 | if (resultSolutions.ContainsKey(result.Key)) {
|
---|
458 | resultSolutions[result.Key].Add(classificationSolution);
|
---|
459 | } else {
|
---|
460 | resultSolutions.Add(result.Key, new List<IClassificationSolution>() { classificationSolution });
|
---|
461 | }
|
---|
462 | }
|
---|
463 | }
|
---|
464 | var aggregatedResults = new List<IResult>();
|
---|
465 | foreach (KeyValuePair<string, List<IClassificationSolution>> solutions in resultSolutions) {
|
---|
466 | // clone manually to correctly clone references between cloned root objects
|
---|
467 | Cloner cloner = new Cloner();
|
---|
468 | var problemDataClone = (IClassificationProblemData)cloner.Clone(Problem.ProblemData);
|
---|
469 | // set partitions of problem data clone correctly
|
---|
470 | problemDataClone.TrainingPartition.Start = SamplesStart.Value; problemDataClone.TrainingPartition.End = SamplesEnd.Value;
|
---|
471 | problemDataClone.TestPartition.Start = SamplesStart.Value; problemDataClone.TestPartition.End = SamplesEnd.Value;
|
---|
472 | // clone models
|
---|
473 | var ensembleSolution = new ClassificationEnsembleSolution(problemDataClone);
|
---|
474 | ensembleSolution.AddClassificationSolutions(solutions.Value);
|
---|
475 |
|
---|
476 | aggregatedResults.Add(new Result(solutions.Key + " (ensemble)", ensembleSolution));
|
---|
477 | }
|
---|
478 | List<IResult> flattenedResults = new List<IResult>();
|
---|
479 | CollectResultsRecursively("", aggregatedResults, flattenedResults);
|
---|
480 | return flattenedResults;
|
---|
481 | }
|
---|
482 |
|
---|
483 | private void CollectResultsRecursively(string path, IEnumerable<IResult> results, IList<IResult> flattenedResults) {
|
---|
484 | foreach (IResult result in results) {
|
---|
485 | flattenedResults.Add(new Result(path + result.Name, result.Value));
|
---|
486 | ResultCollection childCollection = result.Value as ResultCollection;
|
---|
487 | if (childCollection != null) {
|
---|
488 | CollectResultsRecursively(path + result.Name + ".", childCollection, flattenedResults);
|
---|
489 | }
|
---|
490 | }
|
---|
491 | }
|
---|
492 |
|
---|
493 | private static IEnumerable<IResult> ExtractAndAggregateResults<T>(IEnumerable<KeyValuePair<string, IItem>> results)
|
---|
494 | where T : class, IItem, new() {
|
---|
495 | Dictionary<string, List<double>> resultValues = new Dictionary<string, List<double>>();
|
---|
496 | foreach (var resultValue in results.Where(r => r.Value.GetType() == typeof(T))) {
|
---|
497 | if (!resultValues.ContainsKey(resultValue.Key))
|
---|
498 | resultValues[resultValue.Key] = new List<double>();
|
---|
499 | resultValues[resultValue.Key].Add(ConvertToDouble(resultValue.Value));
|
---|
500 | }
|
---|
501 |
|
---|
502 | DoubleValue doubleValue;
|
---|
503 | if (typeof(T) == typeof(PercentValue))
|
---|
504 | doubleValue = new PercentValue();
|
---|
505 | else if (typeof(T) == typeof(DoubleValue))
|
---|
506 | doubleValue = new DoubleValue();
|
---|
507 | else if (typeof(T) == typeof(IntValue))
|
---|
508 | doubleValue = new DoubleValue();
|
---|
509 | else
|
---|
510 | throw new NotSupportedException();
|
---|
511 |
|
---|
512 | List<IResult> aggregatedResults = new List<IResult>();
|
---|
513 | foreach (KeyValuePair<string, List<double>> resultValue in resultValues) {
|
---|
514 | doubleValue.Value = resultValue.Value.Average();
|
---|
515 | aggregatedResults.Add(new Result(resultValue.Key + " (average)", (IItem)doubleValue.Clone()));
|
---|
516 | doubleValue.Value = resultValue.Value.StandardDeviation();
|
---|
517 | aggregatedResults.Add(new Result(resultValue.Key + " (std.dev.)", (IItem)doubleValue.Clone()));
|
---|
518 | }
|
---|
519 | return aggregatedResults;
|
---|
520 | }
|
---|
521 |
|
---|
522 | private static double ConvertToDouble(IItem item) {
|
---|
523 | if (item is DoubleValue) return ((DoubleValue)item).Value;
|
---|
524 | else if (item is IntValue) return ((IntValue)item).Value;
|
---|
525 | else throw new NotSupportedException("Could not convert any item type to double");
|
---|
526 | }
|
---|
527 | #endregion
|
---|
528 |
|
---|
529 | #region events
|
---|
530 | private void RegisterEvents() {
|
---|
531 | Folds.ValueChanged += new EventHandler(Folds_ValueChanged);
|
---|
532 | RegisterClonedAlgorithmsEvents();
|
---|
533 | }
|
---|
534 | private void Folds_ValueChanged(object sender, EventArgs e) {
|
---|
535 | if (ExecutionState != ExecutionState.Prepared)
|
---|
536 | throw new InvalidOperationException("Can not change number of folds if the execution state is not prepared.");
|
---|
537 | }
|
---|
538 |
|
---|
539 |
|
---|
540 | #region template algorithms events
|
---|
541 | public event EventHandler AlgorithmChanged;
|
---|
542 | private void OnAlgorithmChanged() {
|
---|
543 | EventHandler handler = AlgorithmChanged;
|
---|
544 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
545 | OnProblemChanged();
|
---|
546 | if (Problem == null) ExecutionState = ExecutionState.Stopped;
|
---|
547 | }
|
---|
548 | private void RegisterAlgorithmEvents() {
|
---|
549 | algorithm.ProblemChanged += new EventHandler(Algorithm_ProblemChanged);
|
---|
550 | algorithm.ExecutionStateChanged += new EventHandler(Algorithm_ExecutionStateChanged);
|
---|
551 | if (Problem != null) Problem.Reset += new EventHandler(Problem_Reset);
|
---|
552 | }
|
---|
553 | private void DeregisterAlgorithmEvents() {
|
---|
554 | algorithm.ProblemChanged -= new EventHandler(Algorithm_ProblemChanged);
|
---|
555 | algorithm.ExecutionStateChanged -= new EventHandler(Algorithm_ExecutionStateChanged);
|
---|
556 | if (Problem != null) Problem.Reset -= new EventHandler(Problem_Reset);
|
---|
557 | }
|
---|
558 | private void Algorithm_ProblemChanged(object sender, EventArgs e) {
|
---|
559 | if (algorithm.Problem != null && !(algorithm.Problem is IDataAnalysisProblem)) {
|
---|
560 | algorithm.Problem = problem;
|
---|
561 | throw new ArgumentException("A cross validation algorithm can only contain DataAnalysisProblems.");
|
---|
562 | }
|
---|
563 | if (problem != null) problem.Reset -= new EventHandler(Problem_Reset);
|
---|
564 | problem = (IDataAnalysisProblem)algorithm.Problem;
|
---|
565 | if (problem != null) problem.Reset += new EventHandler(Problem_Reset);
|
---|
566 | OnProblemChanged();
|
---|
567 | }
|
---|
568 | public event EventHandler ProblemChanged;
|
---|
569 | private void OnProblemChanged() {
|
---|
570 | EventHandler handler = ProblemChanged;
|
---|
571 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
572 | ConfigureProblem();
|
---|
573 | }
|
---|
574 |
|
---|
575 | private void Problem_Reset(object sender, EventArgs e) {
|
---|
576 | ConfigureProblem();
|
---|
577 | }
|
---|
578 |
|
---|
579 | private void ConfigureProblem() {
|
---|
580 | SamplesStart.Value = 0;
|
---|
581 | if (Problem != null) {
|
---|
582 | SamplesEnd.Value = Problem.ProblemData.Dataset.Rows;
|
---|
583 |
|
---|
584 | DataAnalysisProblemData problemData = Problem.ProblemData as DataAnalysisProblemData;
|
---|
585 | if (problemData != null) {
|
---|
586 | problemData.TrainingPartitionParameter.Hidden = true;
|
---|
587 | problemData.TestPartitionParameter.Hidden = true;
|
---|
588 | }
|
---|
589 | ISymbolicDataAnalysisProblem symbolicProblem = Problem as ISymbolicDataAnalysisProblem;
|
---|
590 | if (symbolicProblem != null) {
|
---|
591 | symbolicProblem.FitnessCalculationPartitionParameter.Hidden = true;
|
---|
592 | symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
|
---|
593 | symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
|
---|
594 | symbolicProblem.ValidationPartitionParameter.Hidden = true;
|
---|
595 | symbolicProblem.ValidationPartition.Start = 0;
|
---|
596 | symbolicProblem.ValidationPartition.End = 0;
|
---|
597 | }
|
---|
598 | } else
|
---|
599 | SamplesEnd.Value = 0;
|
---|
600 | }
|
---|
601 |
|
---|
602 | private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
|
---|
603 | switch (Algorithm.ExecutionState) {
|
---|
604 | case ExecutionState.Prepared: OnPrepared();
|
---|
605 | break;
|
---|
606 | case ExecutionState.Started: throw new InvalidOperationException("Algorithm template can not be started.");
|
---|
607 | case ExecutionState.Paused: throw new InvalidOperationException("Algorithm template can not be paused.");
|
---|
608 | case ExecutionState.Stopped: OnStopped();
|
---|
609 | break;
|
---|
610 | }
|
---|
611 | }
|
---|
612 | #endregion
|
---|
613 |
|
---|
614 | #region clonedAlgorithms events
|
---|
615 | private void RegisterClonedAlgorithmsEvents() {
|
---|
616 | clonedAlgorithms.ItemsAdded += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
|
---|
617 | clonedAlgorithms.ItemsRemoved += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
|
---|
618 | clonedAlgorithms.CollectionReset += new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
|
---|
619 | foreach (IAlgorithm algorithm in clonedAlgorithms)
|
---|
620 | RegisterClonedAlgorithmEvents(algorithm);
|
---|
621 | }
|
---|
622 | private void DeregisterClonedAlgorithmsEvents() {
|
---|
623 | clonedAlgorithms.ItemsAdded -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsAdded);
|
---|
624 | clonedAlgorithms.ItemsRemoved -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_ItemsRemoved);
|
---|
625 | clonedAlgorithms.CollectionReset -= new CollectionItemsChangedEventHandler<IAlgorithm>(ClonedAlgorithms_CollectionReset);
|
---|
626 | foreach (IAlgorithm algorithm in clonedAlgorithms)
|
---|
627 | DeregisterClonedAlgorithmEvents(algorithm);
|
---|
628 | }
|
---|
629 | private void ClonedAlgorithms_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
|
---|
630 | foreach (IAlgorithm algorithm in e.Items)
|
---|
631 | RegisterClonedAlgorithmEvents(algorithm);
|
---|
632 | }
|
---|
633 | private void ClonedAlgorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
|
---|
634 | foreach (IAlgorithm algorithm in e.Items)
|
---|
635 | DeregisterClonedAlgorithmEvents(algorithm);
|
---|
636 | }
|
---|
637 | private void ClonedAlgorithms_CollectionReset(object sender, CollectionItemsChangedEventArgs<IAlgorithm> e) {
|
---|
638 | foreach (IAlgorithm algorithm in e.OldItems)
|
---|
639 | DeregisterClonedAlgorithmEvents(algorithm);
|
---|
640 | foreach (IAlgorithm algorithm in e.Items)
|
---|
641 | RegisterClonedAlgorithmEvents(algorithm);
|
---|
642 | }
|
---|
643 | private void RegisterClonedAlgorithmEvents(IAlgorithm algorithm) {
|
---|
644 | algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
|
---|
645 | algorithm.ExecutionTimeChanged += new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
|
---|
646 | algorithm.Started += new EventHandler(ClonedAlgorithm_Started);
|
---|
647 | algorithm.Paused += new EventHandler(ClonedAlgorithm_Paused);
|
---|
648 | algorithm.Stopped += new EventHandler(ClonedAlgorithm_Stopped);
|
---|
649 | }
|
---|
650 | private void DeregisterClonedAlgorithmEvents(IAlgorithm algorithm) {
|
---|
651 | algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(ClonedAlgorithm_ExceptionOccurred);
|
---|
652 | algorithm.ExecutionTimeChanged -= new EventHandler(ClonedAlgorithm_ExecutionTimeChanged);
|
---|
653 | algorithm.Started -= new EventHandler(ClonedAlgorithm_Started);
|
---|
654 | algorithm.Paused -= new EventHandler(ClonedAlgorithm_Paused);
|
---|
655 | algorithm.Stopped -= new EventHandler(ClonedAlgorithm_Stopped);
|
---|
656 | }
|
---|
657 | private void ClonedAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
|
---|
658 | OnExceptionOccurred(e.Value);
|
---|
659 | }
|
---|
660 | private void ClonedAlgorithm_ExecutionTimeChanged(object sender, EventArgs e) {
|
---|
661 | OnExecutionTimeChanged();
|
---|
662 | }
|
---|
663 |
|
---|
664 | private readonly object locker = new object();
|
---|
665 | private readonly object resultLocker = new object();
|
---|
666 | private void ClonedAlgorithm_Started(object sender, EventArgs e) {
|
---|
667 | IAlgorithm algorithm = sender as IAlgorithm;
|
---|
668 | lock (resultLocker) {
|
---|
669 | if (algorithm != null && !results.ContainsKey(algorithm.Name))
|
---|
670 | results.Add(new Result(algorithm.Name, "Contains results for the specific fold.", algorithm.Results));
|
---|
671 | }
|
---|
672 | }
|
---|
673 |
|
---|
674 | private void ClonedAlgorithm_Paused(object sender, EventArgs e) {
|
---|
675 | lock (locker) {
|
---|
676 | if (pausePending && clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started))
|
---|
677 | OnPaused();
|
---|
678 | }
|
---|
679 | }
|
---|
680 |
|
---|
681 | private void ClonedAlgorithm_Stopped(object sender, EventArgs e) {
|
---|
682 | lock (locker) {
|
---|
683 | if (!stopPending && ExecutionState == ExecutionState.Started) {
|
---|
684 | IAlgorithm preparedAlgorithm = clonedAlgorithms.FirstOrDefault(alg => alg.ExecutionState == ExecutionState.Prepared ||
|
---|
685 | alg.ExecutionState == ExecutionState.Paused);
|
---|
686 | if (preparedAlgorithm != null) preparedAlgorithm.StartAsync(cancellationToken);
|
---|
687 | }
|
---|
688 | if (ExecutionState != ExecutionState.Stopped) {
|
---|
689 | if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
|
---|
690 | OnStopped();
|
---|
691 | else if (stopPending &&
|
---|
692 | clonedAlgorithms.All(
|
---|
693 | alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
|
---|
694 | OnStopped();
|
---|
695 | }
|
---|
696 | }
|
---|
697 | }
|
---|
698 | #endregion
|
---|
699 | #endregion
|
---|
700 |
|
---|
701 | #region event firing
|
---|
702 | public event EventHandler ExecutionStateChanged;
|
---|
703 | private void OnExecutionStateChanged() {
|
---|
704 | EventHandler handler = ExecutionStateChanged;
|
---|
705 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
706 | }
|
---|
707 | public event EventHandler ExecutionTimeChanged;
|
---|
708 | private void OnExecutionTimeChanged() {
|
---|
709 | EventHandler handler = ExecutionTimeChanged;
|
---|
710 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
711 | }
|
---|
712 | public event EventHandler Prepared;
|
---|
713 | private void OnPrepared() {
|
---|
714 | ExecutionState = ExecutionState.Prepared;
|
---|
715 | EventHandler handler = Prepared;
|
---|
716 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
717 | OnExecutionTimeChanged();
|
---|
718 | }
|
---|
719 | public event EventHandler Started;
|
---|
720 | private void OnStarted() {
|
---|
721 | ExecutionState = ExecutionState.Started;
|
---|
722 | EventHandler handler = Started;
|
---|
723 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
724 | }
|
---|
725 | public event EventHandler Paused;
|
---|
726 | private void OnPaused() {
|
---|
727 | pausePending = false;
|
---|
728 | ExecutionState = ExecutionState.Paused;
|
---|
729 | signaler.Set();
|
---|
730 | EventHandler handler = Paused;
|
---|
731 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
732 | }
|
---|
733 | public event EventHandler Stopped;
|
---|
734 | private void OnStopped() {
|
---|
735 | stopPending = false;
|
---|
736 | Dictionary<string, IItem> collectedResults = new Dictionary<string, IItem>();
|
---|
737 | AggregateResultValues(collectedResults);
|
---|
738 | results.AddRange(collectedResults.Select(x => new Result(x.Key, x.Value)).Cast<IResult>().ToArray());
|
---|
739 | runsCounter++;
|
---|
740 | runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
|
---|
741 | ExecutionState = ExecutionState.Stopped;
|
---|
742 | signaler.Set();
|
---|
743 | EventHandler handler = Stopped;
|
---|
744 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
745 | }
|
---|
746 | public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
|
---|
747 | private void OnExceptionOccurred(Exception exception) {
|
---|
748 | EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
|
---|
749 | if (handler != null) handler(this, new EventArgs<Exception>(exception));
|
---|
750 | }
|
---|
751 | public event EventHandler StoreAlgorithmInEachRunChanged;
|
---|
752 | private void OnStoreAlgorithmInEachRunChanged() {
|
---|
753 | EventHandler handler = StoreAlgorithmInEachRunChanged;
|
---|
754 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
755 | }
|
---|
756 | #endregion
|
---|
757 | }
|
---|
758 | }
|
---|