Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.LinqExpressionTreeInterpreter/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Crossovers/SymbolicDataAnalysisExpressionSemanticSimilarityCrossover.cs @ 12940

Last change on this file since 12940 was 12422, checked in by mkommend, 9 years ago

#2320: Merged the encoding class and all accompanying changes in the trunk.

File size: 6.7 KB
Line 
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
22using System.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Random;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [Item("SemanticSimilarityCrossover", "An operator which performs subtree swapping based on the notion semantic similarity between subtrees\n" +
34                                       "(criteria: mean of the absolute differences between the estimated output values of the two subtrees, falling into a user-defined range)\n" +
35                                       "- Take two parent individuals P0 and P1\n" +
36                                       "- Randomly choose a node N from the P0\n" +
37                                       "- Find the first node M that satisfies the semantic similarity criteria\n" +
38                                       "- Swap N for M and return P0")]
39  public sealed class SymbolicDataAnalysisExpressionSemanticSimilarityCrossover<T> : SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
40    private const string SemanticSimilarityRangeParameterName = "SemanticSimilarityRange";
41
42    #region Parameter properties
43    public IValueParameter<DoubleRange> SemanticSimilarityRangeParameter {
44      get { return (IValueParameter<DoubleRange>)Parameters[SemanticSimilarityRangeParameterName]; }
45    }
46    #endregion
47
48    #region Properties
49    public DoubleRange SemanticSimilarityRange {
50      get { return SemanticSimilarityRangeParameter.Value; }
51    }
52    #endregion
53
54    [StorableConstructor]
55    private SymbolicDataAnalysisExpressionSemanticSimilarityCrossover(bool deserializing) : base(deserializing) { }
56    private SymbolicDataAnalysisExpressionSemanticSimilarityCrossover(SymbolicDataAnalysisExpressionCrossover<T> original, Cloner cloner) : base(original, cloner) { }
57    public SymbolicDataAnalysisExpressionSemanticSimilarityCrossover()
58      : base() {
59      Parameters.Add(new ValueLookupParameter<DoubleRange>(SemanticSimilarityRangeParameterName, "Semantic similarity interval.", new DoubleRange(0.0001, 10)));
60      name = "SemanticSimilarityCrossover";
61    }
62    public override IDeepCloneable Clone(Cloner cloner) {
63      return new SymbolicDataAnalysisExpressionSemanticSimilarityCrossover<T>(this, cloner);
64    }
65
66    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
67      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
68      List<int> rows = GenerateRowsToEvaluate().ToList();
69      T problemData = ProblemDataParameter.ActualValue;
70      return Cross(random, parent0, parent1, interpreter, problemData, rows, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value, SemanticSimilarityRange);
71    }
72
73    /// <summary>
74    /// Takes two parent individuals P0 and P1.
75    /// Randomly choose a node i from the first parent, then get a node j from the second parent that matches the semantic similarity criteria.
76    /// </summary>
77    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
78                                                T problemData, List<int> rows, int maxDepth, int maxLength, DoubleRange range) {
79      var crossoverPoints0 = new List<CutPoint>();
80      parent0.Root.ForEachNodePostfix((n) => {
81        if (n.Parent != null && n.Parent != parent0.Root)
82          crossoverPoints0.Add(new CutPoint(n.Parent, n));
83      });
84
85      var crossoverPoint0 = crossoverPoints0.SampleRandom(random);
86      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
87      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
88
89      var allowedBranches = new List<ISymbolicExpressionTreeNode>();
90      parent1.Root.ForEachNodePostfix((n) => {
91        if (n.Parent != null && n.Parent != parent1.Root) {
92          if (n.GetDepth() + level <= maxDepth && n.GetLength() + length <= maxLength && crossoverPoint0.IsMatchingPointType(n))
93            allowedBranches.Add(n);
94        }
95      });
96
97      if (allowedBranches.Count == 0)
98        return parent0;
99
100      var dataset = problemData.Dataset;
101
102      // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated
103      var rootSymbol = new ProgramRootSymbol();
104      var startSymbol = new StartSymbol();
105      var tree0 = CreateTreeFromNode(random, crossoverPoint0.Child, rootSymbol, startSymbol);
106      List<double> estimatedValues0 = interpreter.GetSymbolicExpressionTreeValues(tree0, dataset, rows).ToList();
107      crossoverPoint0.Child.Parent = crossoverPoint0.Parent; // restore parent
108      ISymbolicExpressionTreeNode selectedBranch = null;
109
110      // pick the first node that fulfills the semantic similarity conditions
111      foreach (var node in allowedBranches) {
112        var parent = node.Parent;
113        var tree1 = CreateTreeFromNode(random, node, startSymbol, rootSymbol); // this will affect node.Parent
114        List<double> estimatedValues1 = interpreter.GetSymbolicExpressionTreeValues(tree1, dataset, rows).ToList();
115        node.Parent = parent; // restore parent
116
117        OnlineCalculatorError errorState;
118        double ssd = OnlineMeanAbsoluteErrorCalculator.Calculate(estimatedValues0, estimatedValues1, out errorState);
119
120        if (range.Start <= ssd && ssd <= range.End) {
121          selectedBranch = node;
122          break;
123        }
124      }
125
126      // perform the actual swap
127      if (selectedBranch != null)
128        Swap(crossoverPoint0, selectedBranch);
129      return parent0;
130    }
131  }
132}
Note: See TracBrowser for help on using the repository browser.