Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3136_Structural_GP/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/StructuredSymbolicRegressionSingleObjectiveProblem.cs @ 18076

Last change on this file since 18076 was 18076, checked in by dpiringe, 2 years ago

#3136

  • added new parameters
  • added the builded tree into the scope, this allows operators to use the final tree
  • added new operators
File size: 11.2 KB
RevLine 
[18061]1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using HeuristicLab.Core;
7using HeuristicLab.Optimization;
8using HEAL.Attic;
9using HeuristicLab.Common;
10using HeuristicLab.Problems.Instances;
11using HeuristicLab.Parameters;
12using HeuristicLab.Data;
[18062]13using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[18075]14using HeuristicLab.PluginInfrastructure;
[18061]15
[18063]16namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
[18061]17  [StorableType("7464E84B-65CC-440A-91F0-9FA920D730F9")]
[18063]18  [Item(Name = "Structured Symbolic Regression Single Objective Problem (single-objective)", Description = "A problem with a structural definition and unfixed subfunctions.")]
19  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 150)]
[18075]20  public class StructuredSymbolicRegressionSingleObjectiveProblem : SingleObjectiveBasicProblem<MultiEncoding>, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData> {
[18061]21
22    #region Constants
23    private const string ProblemDataParameterName = "ProblemData";
[18063]24    private const string StructureTemplateParameterName = "Structure Template";
[18075]25    private const string InterpreterParameterName = "Interpreter";
[18076]26    private const string EstimationLimitsParameterName = "EstimationLimits";
27    private const string BestTrainingSolutionParameterName = "Best Training Solution";
[18072]28
[18076]29    private const string SymbolicExpressionTreeName = "SymbolicExpressionTree";
30
31    private const string StructureTemplateDescriptionText =
[18072]32      "Enter your expression as string in infix format into the empty input field.\n" +
33      "By checking the \"Apply Linear Scaling\" checkbox you can add the relevant scaling terms to your expression.\n" +
34      "After entering the expression click parse to build the tree.\n" +
35      "To edit the defined sub-functions, click on the coressponding colored node in the tree view.";
[18061]36    #endregion
37
[18072]38    #region Parameters
[18061]39    public IValueParameter<IRegressionProblemData> ProblemDataParameter => (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
[18063]40    public IFixedValueParameter<StructureTemplate> StructureTemplateParameter => (IFixedValueParameter<StructureTemplate>)Parameters[StructureTemplateParameterName];
[18075]41    public IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> InterpreterParameter => (IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[InterpreterParameterName];
[18076]42    public IFixedValueParameter<DoubleLimit> EstimationLimitsParameter => (IFixedValueParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName];
43    public IResultParameter<ISymbolicRegressionSolution> BestTrainingSolutionParameter => (IResultParameter<ISymbolicRegressionSolution>)Parameters[BestTrainingSolutionParameterName];
[18061]44    #endregion
45
46    #region Properties
[18076]47    public IRegressionProblemData ProblemData {
48      get => ProblemDataParameter.Value;
[18061]49      set {
50        ProblemDataParameter.Value = value;
51        ProblemDataChanged?.Invoke(this, EventArgs.Empty);
52      }
53    }
54
[18075]55    public StructureTemplate StructureTemplate => StructureTemplateParameter.Value;
[18061]56
[18075]57    public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter => InterpreterParameter.Value;
[18063]58
[18061]59    IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
60    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
61
[18076]62    public DoubleLimit EstimationLimits => EstimationLimitsParameter.Value;
63
[18066]64    public override bool Maximization => true;
[18061]65    #endregion
66
67    #region EventHandlers
68    public event EventHandler ProblemDataChanged;
69    #endregion
70
71    #region Constructors & Cloning
72    public StructuredSymbolicRegressionSingleObjectiveProblem() {
[18062]73      var problemData = new ShapeConstrainedRegressionProblemData();
[18076]74      var targetInterval = problemData.VariableRanges.GetInterval(problemData.TargetVariable);
75      var estimationWidth = targetInterval.Width * 10;
[18062]76
[18076]77
[18065]78      var structureTemplate = new StructureTemplate();
[18066]79      structureTemplate.Changed += OnTemplateChanged;
[18065]80
[18075]81      Parameters.Add(new ValueParameter<IRegressionProblemData>(
[18076]82        ProblemDataParameterName,
[18075]83        problemData));
84      Parameters.Add(new FixedValueParameter<StructureTemplate>(
[18076]85        StructureTemplateParameterName,
86        StructureTemplateDescriptionText,
[18075]87        structureTemplate));
88      Parameters.Add(new ValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(
[18076]89        InterpreterParameterName,
90        new SymbolicDataAnalysisExpressionTreeInterpreter()) { Hidden = true });
91      Parameters.Add(new FixedValueParameter<DoubleLimit>(
92        EstimationLimitsParameterName,
93        new DoubleLimit(targetInterval.LowerBound - estimationWidth, targetInterval.UpperBound + estimationWidth)));
94      Parameters.Add(new ResultParameter<ISymbolicRegressionSolution>(BestTrainingSolutionParameterName, ""));
[18075]95
96      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
[18076]97
98      Operators.Add(new SymbolicDataAnalysisVariableFrequencyAnalyzer());
99      Operators.Add(new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer());
100      //TODO change to value lookup
101      //Operators.Add(new SymbolicExpressionTreeLengthAnalyzer());
102      Operators.Add(new SymbolicExpressionSymbolFrequencyAnalyzer());
103
[18061]104    }
105
[18076]106    public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original,
107      Cloner cloner) : base(original, cloner) { }
[18061]108
109    [StorableConstructor]
[18063]110    protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
[18065]111    #endregion
[18061]112
[18065]113    #region Cloning
[18061]114    public override IDeepCloneable Clone(Cloner cloner) =>
115      new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
116    #endregion
117
[18075]118    private void ProblemDataParameterValueChanged(object sender, EventArgs e) {
119      StructureTemplate.Reset();
120      // InfoBox for Reset?
121    }
122
[18066]123    private void OnTemplateChanged(object sender, EventArgs args) {
[18068]124      SetupStructureTemplate();
125    }
126
127    private void SetupStructureTemplate() {
[18066]128      foreach (var e in Encoding.Encodings.ToArray())
129        Encoding.Remove(e);
130
[18068]131      foreach (var f in StructureTemplate.SubFunctions.Values) {
132        SetupVariables(f);
[18075]133        if (!Encoding.Encodings.Any(x => x.Name == f.Name)) // to prevent the same encoding twice
134          Encoding.Add(new SymbolicExpressionTreeEncoding(
[18076]135            f.Name,
136            f.Grammar,
137            f.MaximumSymbolicExpressionTreeLength,
[18075]138            f.MaximumSymbolicExpressionTreeDepth));
[18066]139      }
140    }
141
142    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
143      base.Analyze(individuals, qualities, results, random);
144
[18076]145      var orderedIndividuals = individuals.Zip(qualities, (i, q) => new { Individual = i, Quality = q }).OrderBy(z => z.Quality);
146      var best = Maximization ? orderedIndividuals.Last().Individual : orderedIndividuals.First().Individual;
147
148      if (!results.ContainsKey(BestTrainingSolutionParameter.ActualName)) {
149        results.Add(new Result(BestTrainingSolutionParameter.ActualName, typeof(SymbolicRegressionSolution)));
[18066]150      }
151
[18076]152      var tree = (ISymbolicExpressionTree)best[SymbolicExpressionTreeName];
153
154      var model = new SymbolicRegressionModel(ProblemData.TargetVariable, tree, Interpreter);
155      var solution = model.CreateRegressionSolution(ProblemData);
156
157      results[BestTrainingSolutionParameter.ActualName].Value = solution;
[18066]158    }
159
[18076]160
[18065]161    public override double Evaluate(Individual individual, IRandom random) {
[18066]162      var tree = BuildTree(individual);
[18071]163
[18072]164      if (StructureTemplate.ApplyLinearScaling)
[18076]165        AdjustLinearScalingParams(ProblemData, tree, Interpreter);
166
167      individual[SymbolicExpressionTreeName] = tree;
168
[18066]169      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
[18076]170        Interpreter, tree,
171        EstimationLimits.Lower, EstimationLimits.Upper,
[18066]172        ProblemData, ProblemData.TrainingIndices, false);
[18076]173
[18066]174      return quality;
175    }
176
[18076]177    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
[18071]178      var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
179      var scalingNode = offsetNode.Subtrees.Where(x => !(x is ConstantTreeNode)).First();
180
181      var offsetConstantNode = (ConstantTreeNode)offsetNode.Subtrees.Where(x => x is ConstantTreeNode).First();
182      var scalingConstantNode = (ConstantTreeNode)scalingNode.Subtrees.Where(x => x is ConstantTreeNode).First();
183
[18076]184      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
185      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
[18071]186
187      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
[18076]188      if (error == OnlineCalculatorError.None) {
[18071]189        offsetConstantNode.Value = a;
190        scalingConstantNode.Value = b;
191      }
192    }
193
[18066]194    private ISymbolicExpressionTree BuildTree(Individual individual) {
[18075]195      if (StructureTemplate.Tree == null)
196        throw new ArgumentException("No structure template defined!");
197
[18065]198      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
[18066]199
[18065]200      // build main tree
[18076]201      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
202        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
[18062]203
[18076]204        // add new tree
205        var subTree = subFunctionTree.Root.GetSubtree(0)  // Start
206                                          .GetSubtree(0); // Offset
207        subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
208        subFunctionTreeNode.AddSubtree(subTree);
209
[18065]210      }
[18066]211      return templateTree;
[18061]212    }
213
[18068]214    private void SetupVariables(SubFunction subFunction) {
215      var varSym = (Variable)subFunction.Grammar.GetSymbol("Variable");
216      if (varSym == null) {
217        varSym = new Variable();
218        subFunction.Grammar.AddSymbol(varSym);
219      }
220
221      var allVariables = ProblemData.InputVariables.Select(x => x.Value);
222      var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
223
224      // set all variables
225      varSym.AllVariableNames = allVariables;
226
227      // set all allowed variables
228      if (subFunction.Arguments.Contains("_")) {
229        varSym.VariableNames = allInputs;
230      } else {
231        var vars = new List<string>();
232        var exceptions = new List<Exception>();
233        foreach (var arg in subFunction.Arguments) {
234          if (allInputs.Contains(arg))
235            vars.Add(arg);
236          else
237            exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
238        }
239        if (exceptions.Any())
240          throw new AggregateException(exceptions);
241        varSym.VariableNames = vars;
242      }
243
244      varSym.Enabled = true;
245    }
246
[18075]247    public void Load(IRegressionProblemData data) => ProblemData = data;
[18061]248  }
249}
Note: See TracBrowser for help on using the repository browser.