1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2016 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.Linq;
|
---|
25 | using HeuristicLab.Analysis;
|
---|
26 | using HeuristicLab.Common;
|
---|
27 | using HeuristicLab.Core;
|
---|
28 | using HeuristicLab.Data;
|
---|
29 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
30 | using HeuristicLab.Optimization;
|
---|
31 | using HeuristicLab.Parameters;
|
---|
32 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
33 |
|
---|
34 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
|
---|
35 | [Item("SymbolicRegressionSingleObjectiveOSGAEvaluator", "An evaluator which tries to predict when a child will not be able to fullfil offspring selection criteria, to save evaluation time.")]
|
---|
36 | [StorableClass]
|
---|
37 | public class SymbolicRegressionSingleObjectiveOsgaEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
|
---|
38 | private const string RelativeParentChildQualityThresholdParameterName = "RelativeParentChildQualityThreshold";
|
---|
39 | private const string RelativeFitnessEvaluationIntervalSizeParameterName = "RelativeFitnessEvaluationIntervalSize";
|
---|
40 | private const string ResultCollectionParameterName = "Results";
|
---|
41 |
|
---|
42 | #region parameters
|
---|
43 | public ILookupParameter<ResultCollection> ResultCollectionParameter {
|
---|
44 | get { return (ILookupParameter<ResultCollection>)Parameters[ResultCollectionParameterName]; }
|
---|
45 | }
|
---|
46 | public IFixedValueParameter<IntValue> CorrectlyRejectedParameter {
|
---|
47 | get { return (IFixedValueParameter<IntValue>)Parameters["CorrectlyRejected"]; }
|
---|
48 | }
|
---|
49 | public IFixedValueParameter<IntValue> IncorrectlyRejectedParameter {
|
---|
50 | get { return (IFixedValueParameter<IntValue>)Parameters["IncorrectlyRejected"]; }
|
---|
51 | }
|
---|
52 | public IFixedValueParameter<IntValue> CorrectlyNotRejectedParameter {
|
---|
53 | get { return (IFixedValueParameter<IntValue>)Parameters["CorrectlyNotRejected"]; }
|
---|
54 | }
|
---|
55 | public IFixedValueParameter<IntValue> IncorrectlyNotRejectedParameter {
|
---|
56 | get { return (IFixedValueParameter<IntValue>)Parameters["IncorrectlyNotRejected"]; }
|
---|
57 | }
|
---|
58 | public IValueLookupParameter<DoubleValue> ComparisonFactorParameter {
|
---|
59 | get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactor"]; }
|
---|
60 | }
|
---|
61 | public IFixedValueParameter<PercentValue> RelativeParentChildQualityThresholdParameter {
|
---|
62 | get { return (IFixedValueParameter<PercentValue>)Parameters[RelativeParentChildQualityThresholdParameterName]; }
|
---|
63 | }
|
---|
64 | public IFixedValueParameter<PercentValue> RelativeFitnessEvaluationIntervalSizeParameter {
|
---|
65 | get { return (IFixedValueParameter<PercentValue>)Parameters[RelativeFitnessEvaluationIntervalSizeParameterName]; }
|
---|
66 | }
|
---|
67 | public IScopeTreeLookupParameter<DoubleValue> ParentQualitiesParameter { get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["ParentQualities"]; } }
|
---|
68 | #endregion
|
---|
69 |
|
---|
70 | #region parameter properties
|
---|
71 | public double RelativeParentChildQualityThreshold {
|
---|
72 | get { return RelativeParentChildQualityThresholdParameter.Value.Value; }
|
---|
73 | set { RelativeParentChildQualityThresholdParameter.Value.Value = value; }
|
---|
74 | }
|
---|
75 |
|
---|
76 | public double RelativeFitnessEvaluationIntervalSize {
|
---|
77 | get { return RelativeFitnessEvaluationIntervalSizeParameter.Value.Value; }
|
---|
78 | set { RelativeFitnessEvaluationIntervalSizeParameter.Value.Value = value; }
|
---|
79 | }
|
---|
80 |
|
---|
81 | public int CorrectlyRejected {
|
---|
82 | get { return CorrectlyRejectedParameter.Value.Value; }
|
---|
83 | set { CorrectlyRejectedParameter.Value.Value = value; }
|
---|
84 | }
|
---|
85 |
|
---|
86 | public int CorrectlyNotRejected {
|
---|
87 | get { return CorrectlyNotRejectedParameter.Value.Value; }
|
---|
88 | set { CorrectlyNotRejectedParameter.Value.Value = value; }
|
---|
89 | }
|
---|
90 |
|
---|
91 | public int IncorrectlyRejected {
|
---|
92 | get { return IncorrectlyRejectedParameter.Value.Value; }
|
---|
93 | set { IncorrectlyRejectedParameter.Value.Value = value; }
|
---|
94 | }
|
---|
95 |
|
---|
96 | public int IncorrectlyNotRejected {
|
---|
97 | get { return IncorrectlyNotRejectedParameter.Value.Value; }
|
---|
98 | set { IncorrectlyNotRejectedParameter.Value.Value = value; }
|
---|
99 | }
|
---|
100 | #endregion
|
---|
101 |
|
---|
102 | public override bool Maximization {
|
---|
103 | get { return true; }
|
---|
104 | }
|
---|
105 |
|
---|
106 | public SymbolicRegressionSingleObjectiveOsgaEvaluator() {
|
---|
107 | Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactor", "Determines if the quality should be compared to the better parent (1.0), to the worse (0.0) or to any linearly interpolated value between them."));
|
---|
108 | Parameters.Add(new FixedValueParameter<PercentValue>(RelativeParentChildQualityThresholdParameterName, new PercentValue(0.1)));
|
---|
109 | Parameters.Add(new FixedValueParameter<PercentValue>(RelativeFitnessEvaluationIntervalSizeParameterName, new PercentValue(0.1)));
|
---|
110 | Parameters.Add(new FixedValueParameter<IntValue>("CorrectlyRejected", new IntValue(0)));
|
---|
111 | Parameters.Add(new FixedValueParameter<IntValue>("IncorrectlyRejected", new IntValue(0)));
|
---|
112 | Parameters.Add(new FixedValueParameter<IntValue>("CorrectlyNotRejected", new IntValue(0)));
|
---|
113 | Parameters.Add(new FixedValueParameter<IntValue>("IncorrectlyNotRejected", new IntValue(0)));
|
---|
114 | Parameters.Add(new LookupParameter<ResultCollection>(ResultCollectionParameterName));
|
---|
115 | Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("ParentQualities") { ActualName = "Quality" });
|
---|
116 | }
|
---|
117 |
|
---|
118 | [StorableHook(HookType.AfterDeserialization)]
|
---|
119 | private void AfterDeserialization() {
|
---|
120 | if (!Parameters.ContainsKey(ResultCollectionParameterName))
|
---|
121 | Parameters.Add(new LookupParameter<ResultCollection>(ResultCollectionParameterName));
|
---|
122 |
|
---|
123 | if (!Parameters.ContainsKey("ParentQualities"))
|
---|
124 | Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("ParentQualities") { ActualName = "Quality" });
|
---|
125 | }
|
---|
126 |
|
---|
127 | [StorableConstructor]
|
---|
128 | protected SymbolicRegressionSingleObjectiveOsgaEvaluator(bool deserializing) : base(deserializing) { }
|
---|
129 |
|
---|
130 | protected SymbolicRegressionSingleObjectiveOsgaEvaluator(SymbolicRegressionSingleObjectiveOsgaEvaluator original, Cloner cloner) : base(original, cloner) { }
|
---|
131 |
|
---|
132 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
133 | return new SymbolicRegressionSingleObjectiveOsgaEvaluator(this, cloner);
|
---|
134 | }
|
---|
135 |
|
---|
136 | public override void ClearState() {
|
---|
137 | base.ClearState();
|
---|
138 | CorrectlyNotRejected = 0;
|
---|
139 | CorrectlyRejected = 0;
|
---|
140 | IncorrectlyNotRejected = 0;
|
---|
141 | IncorrectlyRejected = 0;
|
---|
142 | }
|
---|
143 |
|
---|
144 | public override IOperation InstrumentedApply() {
|
---|
145 | var solution = SymbolicExpressionTreeParameter.ActualValue;
|
---|
146 | IEnumerable<int> rows = GenerateRowsToEvaluate();
|
---|
147 |
|
---|
148 | var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
|
---|
149 | var estimationLimits = EstimationLimitsParameter.ActualValue;
|
---|
150 | var problemData = ProblemDataParameter.ActualValue;
|
---|
151 | var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value;
|
---|
152 |
|
---|
153 | double quality;
|
---|
154 | var parentQualities = ParentQualitiesParameter.ActualValue;
|
---|
155 |
|
---|
156 | // parent subscopes are not present during evaluation of the initial population
|
---|
157 | if (parentQualities.Length > 0) {
|
---|
158 | quality = Calculate(interpreter, solution, estimationLimits, problemData, rows, applyLinearScaling);
|
---|
159 | } else {
|
---|
160 | quality = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData, rows, applyLinearScaling);
|
---|
161 | }
|
---|
162 | QualityParameter.ActualValue = new DoubleValue(quality);
|
---|
163 |
|
---|
164 | return base.InstrumentedApply();
|
---|
165 | }
|
---|
166 |
|
---|
167 | public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling) {
|
---|
168 | IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows);
|
---|
169 | IEnumerable<double> targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
|
---|
170 | OnlineCalculatorError errorState;
|
---|
171 |
|
---|
172 | double r;
|
---|
173 | if (applyLinearScaling) {
|
---|
174 | var rCalculator = new OnlinePearsonsRCalculator();
|
---|
175 | CalculateWithScaling(targetValues, estimatedValues, lowerEstimationLimit, upperEstimationLimit, rCalculator, problemData.Dataset.Rows);
|
---|
176 | errorState = rCalculator.ErrorState;
|
---|
177 | r = rCalculator.R;
|
---|
178 | } else {
|
---|
179 | IEnumerable<double> boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
|
---|
180 | r = OnlinePearsonsRCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState);
|
---|
181 | }
|
---|
182 | if (errorState != OnlineCalculatorError.None) return double.NaN;
|
---|
183 | return r * r;
|
---|
184 | }
|
---|
185 |
|
---|
186 | private double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, DoubleLimit estimationLimits, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling) {
|
---|
187 | var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows).ToList();
|
---|
188 | var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
|
---|
189 | IEnumerator<double> targetValuesEnumerator;
|
---|
190 |
|
---|
191 | double alpha = 0, beta = 1;
|
---|
192 | if (applyLinearScaling) {
|
---|
193 | var linearScalingCalculator = new OnlineLinearScalingParameterCalculator();
|
---|
194 | targetValuesEnumerator = targetValues.GetEnumerator();
|
---|
195 | var estimatedValuesEnumerator = estimatedValues.GetEnumerator();
|
---|
196 | while (targetValuesEnumerator.MoveNext() & estimatedValuesEnumerator.MoveNext()) {
|
---|
197 | double target = targetValuesEnumerator.Current;
|
---|
198 | double estimated = estimatedValuesEnumerator.Current;
|
---|
199 | if (!double.IsNaN(estimated) && !double.IsInfinity(estimated))
|
---|
200 | linearScalingCalculator.Add(estimated, target);
|
---|
201 | }
|
---|
202 | if (linearScalingCalculator.ErrorState == OnlineCalculatorError.None && (targetValuesEnumerator.MoveNext() || estimatedValuesEnumerator.MoveNext()))
|
---|
203 | throw new ArgumentException("Number of elements in target and estimated values enumeration do not match.");
|
---|
204 |
|
---|
205 | alpha = linearScalingCalculator.Alpha;
|
---|
206 | beta = linearScalingCalculator.Beta;
|
---|
207 | if (linearScalingCalculator.ErrorState != OnlineCalculatorError.None) {
|
---|
208 | alpha = 0.0;
|
---|
209 | beta = 1.0;
|
---|
210 | }
|
---|
211 | }
|
---|
212 | var scaledEstimatedValuesEnumerator = estimatedValues.Select(x => x * beta + alpha).LimitToRange(estimationLimits.Lower, estimationLimits.Upper).GetEnumerator();
|
---|
213 | targetValuesEnumerator = targetValues.GetEnumerator();
|
---|
214 |
|
---|
215 | var pearsonRCalculator = new OnlinePearsonsRCalculator();
|
---|
216 |
|
---|
217 | var interval = (int)Math.Floor(problemData.TrainingPartition.Size * RelativeFitnessEvaluationIntervalSize);
|
---|
218 | var i = 0;
|
---|
219 | var qualityPerInterval = new List<double>();
|
---|
220 | while (targetValuesEnumerator.MoveNext() && scaledEstimatedValuesEnumerator.MoveNext()) {
|
---|
221 | pearsonRCalculator.Add(targetValuesEnumerator.Current, scaledEstimatedValuesEnumerator.Current);
|
---|
222 | ++i;
|
---|
223 | if (i % interval == 0) {
|
---|
224 | var q = pearsonRCalculator.ErrorState != OnlineCalculatorError.None ? double.NaN : pearsonRCalculator.R;
|
---|
225 | qualityPerInterval.Add(q * q);
|
---|
226 | }
|
---|
227 | }
|
---|
228 | var r = pearsonRCalculator.ErrorState != OnlineCalculatorError.None ? double.NaN : pearsonRCalculator.R;
|
---|
229 | var actualQuality = r * r;
|
---|
230 | var parentQualities = ParentQualitiesParameter.ActualValue.Select(x => x.Value);
|
---|
231 | var minQuality = parentQualities.Min();
|
---|
232 | var maxQuality = parentQualities.Max();
|
---|
233 | var comparisonFactor = ComparisonFactorParameter.ActualValue.Value;
|
---|
234 | var parentQuality = minQuality + (maxQuality - minQuality) * comparisonFactor;
|
---|
235 | var threshold = parentQuality * RelativeParentChildQualityThreshold;
|
---|
236 |
|
---|
237 | //var predictedRejected = qualityPerInterval.Any(x => double.IsNaN(x) || !(x > threshold));
|
---|
238 |
|
---|
239 | bool predictedRejected = false;
|
---|
240 |
|
---|
241 | DataTable table;
|
---|
242 | var results = ResultCollectionParameter.ActualValue;
|
---|
243 | if (!results.ContainsKey("RejectionCounts")) {
|
---|
244 | table = new DataTable("RejectionCounts");
|
---|
245 | results.Add(new Result("RejectionCounts", table));
|
---|
246 |
|
---|
247 | var row = new DataRow("Predicted Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Histogram } };
|
---|
248 | table.Rows.Add(row);
|
---|
249 |
|
---|
250 | row = new DataRow("Actually Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Histogram } };
|
---|
251 | table.Rows.Add(row);
|
---|
252 |
|
---|
253 | // row = new DataRow("Actually Not Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Columns, StartIndexZero = true } };
|
---|
254 | // row.Values.AddRange(qualityPerInterval.Select(x => 0.0));
|
---|
255 | // table.Rows.Add(row);
|
---|
256 | //
|
---|
257 | // row = new DataRow("Predicted Not Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Columns, StartIndexZero = true } };
|
---|
258 | // row.Values.AddRange(qualityPerInterval.Select(x => 0.0));
|
---|
259 | // table.Rows.Add(row);
|
---|
260 | } else {
|
---|
261 | table = (DataTable)results["RejectionCounts"].Value;
|
---|
262 | }
|
---|
263 |
|
---|
264 | i = 0;
|
---|
265 | foreach (var q in qualityPerInterval) {
|
---|
266 | if (double.IsNaN(q) || !(q > threshold)) {
|
---|
267 | predictedRejected = true;
|
---|
268 | break;
|
---|
269 | }
|
---|
270 | ++i;
|
---|
271 | }
|
---|
272 |
|
---|
273 | var actuallyRejected = !(actualQuality > parentQuality);
|
---|
274 | if (predictedRejected) {
|
---|
275 | table.Rows["Predicted Rejected"].Values.Add(i);
|
---|
276 | if (actuallyRejected)
|
---|
277 | table.Rows["Actually Rejected"].Values.Add(i);
|
---|
278 | }
|
---|
279 | // else {
|
---|
280 | // table.Rows["Predicted Not Rejected"].Values[i]++;
|
---|
281 | // if (!actuallyRejected)
|
---|
282 | // table.Rows["Actually Not Rejected"].Values[i]++;
|
---|
283 | // }
|
---|
284 |
|
---|
285 | if (predictedRejected) {
|
---|
286 | if (actuallyRejected) {
|
---|
287 | CorrectlyRejected++;
|
---|
288 | } else {
|
---|
289 | IncorrectlyRejected++;
|
---|
290 | }
|
---|
291 | } else {
|
---|
292 | if (actuallyRejected) {
|
---|
293 | IncorrectlyNotRejected++;
|
---|
294 | } else {
|
---|
295 | CorrectlyNotRejected++;
|
---|
296 | }
|
---|
297 | }
|
---|
298 | return r * r;
|
---|
299 | }
|
---|
300 |
|
---|
301 | public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
|
---|
302 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
|
---|
303 | EstimationLimitsParameter.ExecutionContext = context;
|
---|
304 | ApplyLinearScalingParameter.ExecutionContext = context;
|
---|
305 |
|
---|
306 | var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
|
---|
307 | var estimationLimits = EstimationLimitsParameter.ActualValue;
|
---|
308 | var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value;
|
---|
309 |
|
---|
310 | double r2 = Calculate(interpreter, tree, estimationLimits.Lower, estimationLimits.Upper, problemData, rows, applyLinearScaling);
|
---|
311 |
|
---|
312 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
|
---|
313 | EstimationLimitsParameter.ExecutionContext = null;
|
---|
314 | ApplyLinearScalingParameter.ExecutionContext = null;
|
---|
315 |
|
---|
316 | return r2;
|
---|
317 | }
|
---|
318 | }
|
---|
319 | }
|
---|