#region License Information
/* HeuristicLab
* Copyright (C) 2002-2010 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.Linq;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Operators;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
using HeuristicLab.Problems.DataAnalysis.Regression.Symbolic;
using HeuristicLab.Problems.DataAnalysis.Symbolic;
using System.Collections.Generic;
using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
using HeuristicLab.Problems.DataAnalysis;
using HeuristicLab.Analysis;
using System;
using HeuristicLab.Optimization.Operators;
using HeuristicLab.Problems.DataAnalysis.Evaluators;
namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Analyzers {
///
/// An operator that analyzes the validation best scaled symbolic regression solution.
///
[Item("FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer", "An operator that analyzes the validation best scaled symbolic regression solution.")]
[StorableClass]
public sealed class FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer : SingleSuccessorOperator, ISymbolicRegressionAnalyzer {
private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
private const string SymbolicExpressionTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
private const string ProblemDataParameterName = "ProblemData";
private const string ValidationSamplesStartParameterName = "SamplesStart";
private const string ValidationSamplesEndParameterName = "SamplesEnd";
private const string QualityParameterName = "Quality";
private const string ScaledQualityParameterName = "ScaledQuality";
private const string UpperEstimationLimitParameterName = "UpperEstimationLimit";
private const string LowerEstimationLimitParameterName = "LowerEstimationLimit";
private const string AlphaParameterName = "Alpha";
private const string BetaParameterName = "Beta";
private const string BestSolutionParameterName = "Best solution (validation)";
private const string BestSolutionQualityParameterName = "Best solution quality (validation)";
private const string CurrentBestValidationQualityParameterName = "Current best validation quality";
private const string BestSolutionQualityValuesParameterName = "Validation Quality";
private const string ResultsParameterName = "Results";
private const string VariableFrequenciesParameterName = "VariableFrequencies";
private const string BestKnownQualityParameterName = "BestKnownQuality";
private const string GenerationsParameterName = "Generations";
private const string TrainingMeanSquaredErrorQualityParameterName = "Mean squared error (training)";
private const string MinTrainingMeanSquaredErrorQualityParameterName = "Min mean squared error (training)";
private const string MaxTrainingMeanSquaredErrorQualityParameterName = "Max mean squared error (training)";
private const string AverageTrainingMeanSquaredErrorQualityParameterName = "Average mean squared error (training)";
private const string BestTrainingMeanSquaredErrorQualityParameterName = "Best mean squared error (training)";
private const string TrainingAverageRelativeErrorQualityParameterName = "Average relative error (training)";
private const string MinTrainingAverageRelativeErrorQualityParameterName = "Min average relative error (training)";
private const string MaxTrainingAverageRelativeErrorQualityParameterName = "Max average relative error (training)";
private const string AverageTrainingAverageRelativeErrorQualityParameterName = "Average average relative error (training)";
private const string BestTrainingAverageRelativeErrorQualityParameterName = "Best average relative error (training)";
private const string TrainingRSquaredQualityParameterName = "Rē (training)";
private const string MinTrainingRSquaredQualityParameterName = "Min Rē (training)";
private const string MaxTrainingRSquaredQualityParameterName = "Max Rē (training)";
private const string AverageTrainingRSquaredQualityParameterName = "Average Rē (training)";
private const string BestTrainingRSquaredQualityParameterName = "Best Rē (training)";
private const string TestMeanSquaredErrorQualityParameterName = "Mean squared error (test)";
private const string MinTestMeanSquaredErrorQualityParameterName = "Min mean squared error (test)";
private const string MaxTestMeanSquaredErrorQualityParameterName = "Max mean squared error (test)";
private const string AverageTestMeanSquaredErrorQualityParameterName = "Average mean squared error (test)";
private const string BestTestMeanSquaredErrorQualityParameterName = "Best mean squared error (test)";
private const string TestAverageRelativeErrorQualityParameterName = "Average relative error (test)";
private const string MinTestAverageRelativeErrorQualityParameterName = "Min average relative error (test)";
private const string MaxTestAverageRelativeErrorQualityParameterName = "Max average relative error (test)";
private const string AverageTestAverageRelativeErrorQualityParameterName = "Average average relative error (test)";
private const string BestTestAverageRelativeErrorQualityParameterName = "Best average relative error (test)";
private const string TestRSquaredQualityParameterName = "Rē (test)";
private const string MinTestRSquaredQualityParameterName = "Min Rē (test)";
private const string MaxTestRSquaredQualityParameterName = "Max Rē (test)";
private const string AverageTestRSquaredQualityParameterName = "Average Rē (test)";
private const string BestTestRSquaredQualityParameterName = "Best Rē (test)";
private const string RSquaredValuesParameterName = "Rē";
private const string MeanSquaredErrorValuesParameterName = "Mean squared error";
private const string RelativeErrorValuesParameterName = "Average relative error";
#region parameter properties
public ScopeTreeLookupParameter SymbolicExpressionTreeParameter {
get { return (ScopeTreeLookupParameter)Parameters[SymbolicExpressionTreeParameterName]; }
}
public ScopeTreeLookupParameter QualityParameter {
get { return (ScopeTreeLookupParameter)Parameters[QualityParameterName]; }
}
public ScopeTreeLookupParameter AlphaParameter {
get { return (ScopeTreeLookupParameter)Parameters[AlphaParameterName]; }
}
public ScopeTreeLookupParameter BetaParameter {
get { return (ScopeTreeLookupParameter)Parameters[BetaParameterName]; }
}
public IValueLookupParameter SymbolicExpressionTreeInterpreterParameter {
get { return (IValueLookupParameter)Parameters[SymbolicExpressionTreeInterpreterParameterName]; }
}
public IValueLookupParameter ProblemDataParameter {
get { return (IValueLookupParameter)Parameters[ProblemDataParameterName]; }
}
public IValueLookupParameter ValidationSamplesStartParameter {
get { return (IValueLookupParameter)Parameters[ValidationSamplesStartParameterName]; }
}
public IValueLookupParameter ValidationSamplesEndParameter {
get { return (IValueLookupParameter)Parameters[ValidationSamplesEndParameterName]; }
}
public IValueLookupParameter UpperEstimationLimitParameter {
get { return (IValueLookupParameter)Parameters[UpperEstimationLimitParameterName]; }
}
public IValueLookupParameter LowerEstimationLimitParameter {
get { return (IValueLookupParameter)Parameters[LowerEstimationLimitParameterName]; }
}
public ILookupParameter BestSolutionParameter {
get { return (ILookupParameter)Parameters[BestSolutionParameterName]; }
}
public ILookupParameter GenerationsParameter {
get { return (ILookupParameter)Parameters[GenerationsParameterName]; }
}
public ILookupParameter BestSolutionQualityParameter {
get { return (ILookupParameter)Parameters[BestSolutionQualityParameterName]; }
}
public ILookupParameter ResultsParameter {
get { return (ILookupParameter)Parameters[ResultsParameterName]; }
}
public ILookupParameter BestKnownQualityParameter {
get { return (ILookupParameter)Parameters[BestKnownQualityParameterName]; }
}
public ILookupParameter VariableFrequenciesParameter {
get { return (ILookupParameter)Parameters[VariableFrequenciesParameterName]; }
}
#endregion
#region properties
public ItemArray SymbolicExpressionTree {
get { return SymbolicExpressionTreeParameter.ActualValue; }
}
public ItemArray Quality {
get { return QualityParameter.ActualValue; }
}
public ItemArray Alpha {
get { return AlphaParameter.ActualValue; }
}
public ItemArray Beta {
get { return BetaParameter.ActualValue; }
}
public ISymbolicExpressionTreeInterpreter SymbolicExpressionTreeInterpreter {
get { return SymbolicExpressionTreeInterpreterParameter.ActualValue; }
}
public DataAnalysisProblemData ProblemData {
get { return ProblemDataParameter.ActualValue; }
}
public IntValue ValidiationSamplesStart {
get { return ValidationSamplesStartParameter.ActualValue; }
}
public IntValue ValidationSamplesEnd {
get { return ValidationSamplesEndParameter.ActualValue; }
}
public DoubleValue UpperEstimationLimit {
get { return UpperEstimationLimitParameter.ActualValue; }
}
public DoubleValue LowerEstimationLimit {
get { return LowerEstimationLimitParameter.ActualValue; }
}
public ResultCollection Results {
get { return ResultsParameter.ActualValue; }
}
public DataTable VariableFrequencies {
get { return VariableFrequenciesParameter.ActualValue; }
}
public IntValue Generations {
get { return GenerationsParameter.ActualValue; }
}
#endregion
public FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer()
: base() {
Parameters.Add(new ScopeTreeLookupParameter(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
Parameters.Add(new ScopeTreeLookupParameter(QualityParameterName, "The quality of the symbolic expression trees to analyze."));
Parameters.Add(new ScopeTreeLookupParameter(AlphaParameterName, "The alpha parameter for linear scaling."));
Parameters.Add(new ScopeTreeLookupParameter(BetaParameterName, "The beta parameter for linear scaling."));
Parameters.Add(new ValueLookupParameter(SymbolicExpressionTreeInterpreterParameterName, "The interpreter that should be used for the analysis of symbolic expression trees."));
Parameters.Add(new ValueLookupParameter(ProblemDataParameterName, "The problem data for which the symbolic expression tree is a solution."));
Parameters.Add(new ValueLookupParameter(ValidationSamplesStartParameterName, "The first index of the validation partition of the data set."));
Parameters.Add(new ValueLookupParameter(ValidationSamplesEndParameterName, "The last index of the validation partition of the data set."));
Parameters.Add(new ValueLookupParameter(UpperEstimationLimitParameterName, "The upper estimation limit that was set for the evaluation of the symbolic expression trees."));
Parameters.Add(new ValueLookupParameter(LowerEstimationLimitParameterName, "The lower estimation limit that was set for the evaluation of the symbolic expression trees."));
Parameters.Add(new LookupParameter(BestSolutionParameterName, "The best symbolic regression solution."));
Parameters.Add(new LookupParameter(GenerationsParameterName, "The number of generations calculated so far."));
Parameters.Add(new LookupParameter(BestSolutionQualityParameterName, "The quality of the best symbolic regression solution."));
Parameters.Add(new LookupParameter(ResultsParameterName, "The result collection where the best symbolic regression solution should be stored."));
Parameters.Add(new LookupParameter(BestKnownQualityParameterName, "The best known (validation) quality achieved on the data set."));
Parameters.Add(new LookupParameter(VariableFrequenciesParameterName, "The variable frequencies table to use for the calculation of variable impacts"));
}
[StorableConstructor]
private FixedValidationBestScaledSymbolicRegressionSolutionAnalyzer(bool deserializing) : base() { }
public override IOperation Apply() {
var alphas = Alpha;
var betas = Beta;
var trees = SymbolicExpressionTree;
IEnumerable scaledTrees;
if (alphas.Length == trees.Length) {
scaledTrees = from i in Enumerable.Range(0, trees.Length)
select SymbolicRegressionSolutionLinearScaler.Scale(trees[i], alphas[i].Value, betas[i].Value);
} else {
scaledTrees = trees;
}
int trainingStart = ProblemData.TrainingSamplesStart.Value;
int trainingEnd = ProblemData.TrainingSamplesEnd.Value;
int testStart = ProblemData.TestSamplesStart.Value;
int testEnd = ProblemData.TestSamplesEnd.Value;
SymbolicRegressionModelQualityAnalyzer.Analyze(scaledTrees, SymbolicExpressionTreeInterpreter,
UpperEstimationLimit.Value, LowerEstimationLimit.Value,
ProblemData, trainingStart, trainingEnd, testStart, testEnd, Results);
#region validation best model
string targetVariable = ProblemData.TargetVariable.Value;
int validationStart = ValidiationSamplesStart.Value;
int validationEnd = ValidationSamplesEnd.Value;
double upperEstimationLimit = UpperEstimationLimit != null ? UpperEstimationLimit.Value : double.PositiveInfinity;
double lowerEstimationLimit = LowerEstimationLimit != null ? LowerEstimationLimit.Value : double.NegativeInfinity;
double bestValidationMse = double.MaxValue;
SymbolicExpressionTree bestTree = null;
OnlineMeanSquaredErrorEvaluator mseEvaluator = new OnlineMeanSquaredErrorEvaluator();
foreach (var scaledTree in scaledTrees) {
double validationMse = SymbolicRegressionMeanSquaredErrorEvaluator.Calculate(SymbolicExpressionTreeInterpreter, scaledTree,
lowerEstimationLimit, upperEstimationLimit,
ProblemData.Dataset, targetVariable,
Enumerable.Range(validationStart, validationEnd - validationStart));
if (validationMse < bestValidationMse) {
bestValidationMse = validationMse;
bestTree = scaledTree;
}
}
if (BestSolutionQualityParameter.ActualValue == null || BestSolutionQualityParameter.ActualValue.Value > bestValidationMse) {
var model = new SymbolicRegressionModel((ISymbolicExpressionTreeInterpreter)SymbolicExpressionTreeInterpreter.Clone(),
bestTree);
var solution = new SymbolicRegressionSolution(ProblemData, model, lowerEstimationLimit, upperEstimationLimit);
solution.Name = BestSolutionParameterName;
solution.Description = "Best solution on validation partition found over the whole run.";
BestSolutionParameter.ActualValue = solution;
BestSolutionQualityParameter.ActualValue = new DoubleValue(bestValidationMse);
BestSymbolicRegressionSolutionAnalyzer.UpdateBestSolutionResults(solution, ProblemData, Results, Generations, VariableFrequencies);
}
if (!Results.ContainsKey(BestSolutionQualityValuesParameterName)) {
Results.Add(new Result(BestSolutionQualityValuesParameterName, new DataTable(BestSolutionQualityValuesParameterName, BestSolutionQualityValuesParameterName)));
Results.Add(new Result(BestSolutionQualityParameterName, new DoubleValue()));
Results.Add(new Result(CurrentBestValidationQualityParameterName, new DoubleValue()));
}
Results[BestSolutionQualityParameterName].Value = new DoubleValue(BestSolutionQualityParameter.ActualValue.Value);
Results[CurrentBestValidationQualityParameterName].Value = new DoubleValue(bestValidationMse);
DataTable validationValues = (DataTable)Results[BestSolutionQualityValuesParameterName].Value;
AddValue(validationValues, BestSolutionQualityParameter.ActualValue.Value, BestSolutionQualityParameterName, BestSolutionQualityParameterName);
AddValue(validationValues, bestValidationMse, CurrentBestValidationQualityParameterName, CurrentBestValidationQualityParameterName);
#endregion
return base.Apply();
}
[StorableHook(HookType.AfterDeserialization)]
private void Initialize() {
if (!Parameters.ContainsKey(AlphaParameterName)) {
Parameters.Add(new ScopeTreeLookupParameter(AlphaParameterName, "The alpha parameter for linear scaling."));
}
if (!Parameters.ContainsKey(BetaParameterName)) {
Parameters.Add(new ScopeTreeLookupParameter(BetaParameterName, "The beta parameter for linear scaling."));
}
if (!Parameters.ContainsKey(VariableFrequenciesParameterName)) {
Parameters.Add(new LookupParameter(VariableFrequenciesParameterName, "The variable frequencies table to use for the calculation of variable impacts"));
}
if (!Parameters.ContainsKey(GenerationsParameterName)) {
Parameters.Add(new LookupParameter(GenerationsParameterName, "The number of generations calculated so far."));
}
}
private static void AddValue(DataTable table, double data, string name, string description) {
DataRow row;
table.Rows.TryGetValue(name, out row);
if (row == null) {
row = new DataRow(name, description);
row.Values.Add(data);
table.Rows.Add(row);
} else {
row.Values.Add(data);
}
}
}
}