#region License Information /* HeuristicLab * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System; using System.Collections.Generic; using System.Linq; using HeuristicLab.Analysis; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; using HeuristicLab.Optimization; using HeuristicLab.Parameters; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression { [Item("SymbolicRegressionSingleObjectiveOSGAEvaluator", "An evaluator which tries to predict when a child will not be able to fullfil offspring selection criteria, to save evaluation time.")] [StorableClass] public class SymbolicRegressionSingleObjectiveOsgaEvaluator : SymbolicRegressionSingleObjectiveEvaluator { private const string RelativeParentChildQualityThresholdParameterName = "RelativeParentChildQualityThreshold"; private const string RelativeFitnessEvaluationIntervalSizeParameterName = "RelativeFitnessEvaluationIntervalSize"; private const string ResultCollectionParameterName = "Results"; #region parameters public ILookupParameter ResultCollectionParameter { get { return (ILookupParameter)Parameters[ResultCollectionParameterName]; } } public IFixedValueParameter CorrectlyRejectedParameter { get { return (IFixedValueParameter)Parameters["CorrectlyRejected"]; } } public IFixedValueParameter IncorrectlyRejectedParameter { get { return (IFixedValueParameter)Parameters["IncorrectlyRejected"]; } } public IFixedValueParameter CorrectlyNotRejectedParameter { get { return (IFixedValueParameter)Parameters["CorrectlyNotRejected"]; } } public IFixedValueParameter IncorrectlyNotRejectedParameter { get { return (IFixedValueParameter)Parameters["IncorrectlyNotRejected"]; } } public IValueLookupParameter ComparisonFactorParameter { get { return (ValueLookupParameter)Parameters["ComparisonFactor"]; } } public IFixedValueParameter RelativeParentChildQualityThresholdParameter { get { return (IFixedValueParameter)Parameters[RelativeParentChildQualityThresholdParameterName]; } } public IFixedValueParameter RelativeFitnessEvaluationIntervalSizeParameter { get { return (IFixedValueParameter)Parameters[RelativeFitnessEvaluationIntervalSizeParameterName]; } } public IScopeTreeLookupParameter ParentQualitiesParameter { get { return (IScopeTreeLookupParameter)Parameters["ParentQualities"]; } } #endregion #region parameter properties public double RelativeParentChildQualityThreshold { get { return RelativeParentChildQualityThresholdParameter.Value.Value; } set { RelativeParentChildQualityThresholdParameter.Value.Value = value; } } public double RelativeFitnessEvaluationIntervalSize { get { return RelativeFitnessEvaluationIntervalSizeParameter.Value.Value; } set { RelativeFitnessEvaluationIntervalSizeParameter.Value.Value = value; } } public int CorrectlyRejected { get { return CorrectlyRejectedParameter.Value.Value; } set { CorrectlyRejectedParameter.Value.Value = value; } } public int CorrectlyNotRejected { get { return CorrectlyNotRejectedParameter.Value.Value; } set { CorrectlyNotRejectedParameter.Value.Value = value; } } public int IncorrectlyRejected { get { return IncorrectlyRejectedParameter.Value.Value; } set { IncorrectlyRejectedParameter.Value.Value = value; } } public int IncorrectlyNotRejected { get { return IncorrectlyNotRejectedParameter.Value.Value; } set { IncorrectlyNotRejectedParameter.Value.Value = value; } } #endregion public override bool Maximization { get { return true; } } public SymbolicRegressionSingleObjectiveOsgaEvaluator() { Parameters.Add(new ValueLookupParameter("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.")); Parameters.Add(new FixedValueParameter(RelativeParentChildQualityThresholdParameterName, new PercentValue(0.1))); Parameters.Add(new FixedValueParameter(RelativeFitnessEvaluationIntervalSizeParameterName, new PercentValue(0.1))); Parameters.Add(new FixedValueParameter("CorrectlyRejected", new IntValue(0))); Parameters.Add(new FixedValueParameter("IncorrectlyRejected", new IntValue(0))); Parameters.Add(new FixedValueParameter("CorrectlyNotRejected", new IntValue(0))); Parameters.Add(new FixedValueParameter("IncorrectlyNotRejected", new IntValue(0))); Parameters.Add(new LookupParameter(ResultCollectionParameterName)); Parameters.Add(new ScopeTreeLookupParameter("ParentQualities") { ActualName = "Quality" }); } [StorableHook(HookType.AfterDeserialization)] private void AfterDeserialization() { if (!Parameters.ContainsKey(ResultCollectionParameterName)) Parameters.Add(new LookupParameter(ResultCollectionParameterName)); if (!Parameters.ContainsKey("ParentQualities")) Parameters.Add(new ScopeTreeLookupParameter("ParentQualities") { ActualName = "Quality" }); } [StorableConstructor] protected SymbolicRegressionSingleObjectiveOsgaEvaluator(bool deserializing) : base(deserializing) { } protected SymbolicRegressionSingleObjectiveOsgaEvaluator(SymbolicRegressionSingleObjectiveOsgaEvaluator original, Cloner cloner) : base(original, cloner) { } public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicRegressionSingleObjectiveOsgaEvaluator(this, cloner); } public override void ClearState() { base.ClearState(); CorrectlyNotRejected = 0; CorrectlyRejected = 0; IncorrectlyNotRejected = 0; IncorrectlyRejected = 0; } public override IOperation InstrumentedApply() { var solution = SymbolicExpressionTreeParameter.ActualValue; IEnumerable rows = GenerateRowsToEvaluate(); var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue; var estimationLimits = EstimationLimitsParameter.ActualValue; var problemData = ProblemDataParameter.ActualValue; var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; double quality; var parentQualities = ParentQualitiesParameter.ActualValue; // parent subscopes are not present during evaluation of the initial population if (parentQualities.Length > 0) { quality = Calculate(interpreter, solution, estimationLimits, problemData, rows, applyLinearScaling); } else { quality = Calculate(interpreter, solution, estimationLimits.Lower, estimationLimits.Upper, problemData, rows, applyLinearScaling); } QualityParameter.ActualValue = new DoubleValue(quality); return base.InstrumentedApply(); } public static double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, IRegressionProblemData problemData, IEnumerable rows, bool applyLinearScaling) { IEnumerable estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows); IEnumerable targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows); OnlineCalculatorError errorState; double r; if (applyLinearScaling) { var rCalculator = new OnlinePearsonsRCalculator(); CalculateWithScaling(targetValues, estimatedValues, lowerEstimationLimit, upperEstimationLimit, rCalculator, problemData.Dataset.Rows); errorState = rCalculator.ErrorState; r = rCalculator.R; } else { IEnumerable boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit); r = OnlinePearsonsRCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState); } if (errorState != OnlineCalculatorError.None) return double.NaN; return r * r; } private double Calculate(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, DoubleLimit estimationLimits, IRegressionProblemData problemData, IEnumerable rows, bool applyLinearScaling) { var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows).ToList(); var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows); IEnumerator targetValuesEnumerator; double alpha = 0, beta = 1; if (applyLinearScaling) { var linearScalingCalculator = new OnlineLinearScalingParameterCalculator(); targetValuesEnumerator = targetValues.GetEnumerator(); var estimatedValuesEnumerator = estimatedValues.GetEnumerator(); while (targetValuesEnumerator.MoveNext() & estimatedValuesEnumerator.MoveNext()) { double target = targetValuesEnumerator.Current; double estimated = estimatedValuesEnumerator.Current; if (!double.IsNaN(estimated) && !double.IsInfinity(estimated)) linearScalingCalculator.Add(estimated, target); } if (linearScalingCalculator.ErrorState == OnlineCalculatorError.None && (targetValuesEnumerator.MoveNext() || estimatedValuesEnumerator.MoveNext())) throw new ArgumentException("Number of elements in target and estimated values enumeration do not match."); alpha = linearScalingCalculator.Alpha; beta = linearScalingCalculator.Beta; if (linearScalingCalculator.ErrorState != OnlineCalculatorError.None) { alpha = 0.0; beta = 1.0; } } var scaledEstimatedValuesEnumerator = estimatedValues.Select(x => x * beta + alpha).LimitToRange(estimationLimits.Lower, estimationLimits.Upper).GetEnumerator(); targetValuesEnumerator = targetValues.GetEnumerator(); var pearsonRCalculator = new OnlinePearsonsRCalculator(); var interval = (int)Math.Floor(problemData.TrainingPartition.Size * RelativeFitnessEvaluationIntervalSize); var i = 0; var qualityPerInterval = new List(); while (targetValuesEnumerator.MoveNext() && scaledEstimatedValuesEnumerator.MoveNext()) { pearsonRCalculator.Add(targetValuesEnumerator.Current, scaledEstimatedValuesEnumerator.Current); ++i; if (i % interval == 0) { var q = pearsonRCalculator.ErrorState != OnlineCalculatorError.None ? double.NaN : pearsonRCalculator.R; qualityPerInterval.Add(q * q); } } var r = pearsonRCalculator.ErrorState != OnlineCalculatorError.None ? double.NaN : pearsonRCalculator.R; var actualQuality = r * r; var parentQualities = ParentQualitiesParameter.ActualValue.Select(x => x.Value); var minQuality = parentQualities.Min(); var maxQuality = parentQualities.Max(); var comparisonFactor = ComparisonFactorParameter.ActualValue.Value; var parentQuality = minQuality + (maxQuality - minQuality) * comparisonFactor; var threshold = parentQuality * RelativeParentChildQualityThreshold; //var predictedRejected = qualityPerInterval.Any(x => double.IsNaN(x) || !(x > threshold)); bool predictedRejected = false; DataTable table; var results = ResultCollectionParameter.ActualValue; if (!results.ContainsKey("RejectionCounts")) { table = new DataTable("RejectionCounts"); results.Add(new Result("RejectionCounts", table)); var row = new DataRow("Predicted Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Histogram } }; table.Rows.Add(row); row = new DataRow("Actually Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Histogram } }; table.Rows.Add(row); // row = new DataRow("Actually Not Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Columns, StartIndexZero = true } }; // row.Values.AddRange(qualityPerInterval.Select(x => 0.0)); // table.Rows.Add(row); // // row = new DataRow("Predicted Not Rejected") { VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Columns, StartIndexZero = true } }; // row.Values.AddRange(qualityPerInterval.Select(x => 0.0)); // table.Rows.Add(row); } else { table = (DataTable)results["RejectionCounts"].Value; } i = 0; foreach (var q in qualityPerInterval) { if (double.IsNaN(q) || !(q > threshold)) { predictedRejected = true; break; } ++i; } var actuallyRejected = !(actualQuality > parentQuality); if (predictedRejected) { table.Rows["Predicted Rejected"].Values.Add(i); if (actuallyRejected) table.Rows["Actually Rejected"].Values.Add(i); } // else { // table.Rows["Predicted Not Rejected"].Values[i]++; // if (!actuallyRejected) // table.Rows["Actually Not Rejected"].Values[i]++; // } if (predictedRejected) { if (actuallyRejected) { CorrectlyRejected++; } else { IncorrectlyRejected++; } } else { if (actuallyRejected) { IncorrectlyNotRejected++; } else { CorrectlyNotRejected++; } } return r * r; } public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable rows) { SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context; EstimationLimitsParameter.ExecutionContext = context; ApplyLinearScalingParameter.ExecutionContext = context; var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue; var estimationLimits = EstimationLimitsParameter.ActualValue; var applyLinearScaling = ApplyLinearScalingParameter.ActualValue.Value; double r2 = Calculate(interpreter, tree, estimationLimits.Lower, estimationLimits.Upper, problemData, rows, applyLinearScaling); SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null; EstimationLimitsParameter.ExecutionContext = null; ApplyLinearScalingParameter.ExecutionContext = null; return r2; } } }