Changeset 14237


Ignore:
Timestamp:
08/05/16 14:25:28 (3 years ago)
Author:
gkronber
Message:

#2650: work in progress..

Location:
branches/symbreg-factors-2650
Files:
2 added
22 edited

Legend:

Unmodified
Added
Removed
  • branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/GaussianProcess/GaussianProcessClassificationModelCreator.cs

    r14185 r14237  
    6767        HyperparameterGradientsParameter.ActualValue = new RealVector(model.HyperparameterGradients);
    6868        return base.Apply();
    69       } catch (ArgumentException) { } catch (alglib.alglibexception) { }
     69      }
     70      catch (ArgumentException) { }
     71      catch (alglib.alglibexception) { }
    7072      NegativeLogLikelihoodParameter.ActualValue = new DoubleValue(1E300);
    7173      HyperparameterGradientsParameter.ActualValue = new RealVector(Hyperparameter.Count());
  • branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/GradientBoostedTreesAlgorithmStatic.cs

    r14185 r14237  
    148148    // for custom stepping & termination
    149149    public static IGbmState CreateGbmState(IRegressionProblemData problemData, ILossFunction lossFunction, uint randSeed, int maxSize = 3, double r = 0.66, double m = 0.5, double nu = 0.01) {
     150      // check input variables. Only double variables are allowed.
     151      var invalidInputs =
     152        problemData.AllowedInputVariables.Where(name => !problemData.Dataset.VariableHasType<double>(name));
     153      if (invalidInputs.Any())
     154        throw new NotSupportedException("Gradient tree boosting only supports real-valued variables. Unsupported inputs: " + string.Join(", ", invalidInputs));
     155
    150156      return new GbmState(problemData, lossFunction, randSeed, maxSize, r, m, nu);
    151157    }
  • branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/AlglibUtil.cs

    r14185 r14237  
    2020#endregion
    2121
     22using System;
    2223using System.Collections.Generic;
    2324using System.Linq;
     
    2728  public static class AlglibUtil {
    2829    public static double[,] PrepareInputMatrix(IDataset dataset, IEnumerable<string> variables, IEnumerable<int> rows) {
    29       List<string> variablesList = variables.ToList();
     30      // check input variables. Only double variables are allowed.
     31      var invalidInputs =
     32        variables.Where(name => !dataset.VariableHasType<double>(name));
     33      if (invalidInputs.Any())
     34        throw new NotSupportedException("Unsupported inputs: " + string.Join(", ", invalidInputs));
     35
    3036      List<int> rowsList = rows.ToList();
    31 
    32       double[,] matrix = new double[rowsList.Count, variablesList.Count];
     37      double[,] matrix = new double[rowsList.Count, variables.Count()];
    3338
    3439      int col = 0;
     
    4550      return matrix;
    4651    }
     52
    4753    public static double[,] PrepareAndScaleInputMatrix(IDataset dataset, IEnumerable<string> variables, IEnumerable<int> rows, Scaling scaling) {
     54      // check input variables. Only double variables are allowed.
     55      var invalidInputs =
     56        variables.Where(name => !dataset.VariableHasType<double>(name));
     57      if (invalidInputs.Any())
     58        throw new NotSupportedException("Unsupported inputs: " + string.Join(", ", invalidInputs));
     59
    4860      List<string> variablesList = variables.ToList();
    4961      List<int> rowsList = rows.ToList();
     
    6476      return matrix;
    6577    }
     78
     79    /// <summary>
     80    /// Prepares a binary data matrix from a number of factors and specified factor values
     81    /// </summary>
     82    /// <param name="dataset">A dataset that contains the variable values</param>
     83    /// <param name="factorVariables">An enumerable of categorical variables (factors). For each variable an enumerable of values must be specified.</param>
     84    /// <param name="rows">An enumerable of row indices for the dataset</param>
     85    /// <returns></returns>
     86    /// <remarks>Factor variables (categorical variables) are split up into multiple binary variables one for each specified value.</remarks>
     87    public static double[,] PrepareInputMatrix(
     88      IDataset dataset,
     89      IEnumerable<KeyValuePair<string, IEnumerable<string>>> factorVariables,
     90      IEnumerable<int> rows) {
     91      // check input variables. Only string variables are allowed.
     92      var invalidInputs =
     93        factorVariables.Select(kvp => kvp.Key).Where(name => !dataset.VariableHasType<string>(name));
     94      if (invalidInputs.Any())
     95        throw new NotSupportedException("Unsupported inputs: " + string.Join(", ", invalidInputs));
     96
     97      int numBinaryColumns = factorVariables.Sum(kvp => kvp.Value.Count());
     98
     99      List<int> rowsList = rows.ToList();
     100      double[,] matrix = new double[rowsList.Count, numBinaryColumns];
     101
     102      int col = 0;
     103      foreach (var kvp in factorVariables) {
     104        var varName = kvp.Key;
     105        var cats = kvp.Value;
     106        var catCount = cats.Count();
     107        if (catCount == 0) continue;
     108        foreach (var cat in cats) {
     109          var values = dataset.GetStringValues(varName, rows);
     110          int row = 0;
     111          foreach (var value in values) {
     112            matrix[row, col] = value == cat ? 1 : 0;
     113            row++;
     114          }
     115          col++;
     116        }
     117      }
     118      return matrix;
     119    }
    66120  }
    67121}
  • branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/LinearRegression.cs

    r14185 r14237  
    7373      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
    7474      IEnumerable<int> rows = problemData.TrainingIndices;
    75       double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows);
     75      var doubleVariables = allowedInputVariables.Where(dataset.VariableHasType<double>);
     76      var factorVariableNames = allowedInputVariables.Where(dataset.VariableHasType<string>);
     77      var factorVariables = from factor in factorVariableNames
     78                            let distinctValues = dataset.GetStringValues(factor, rows).Distinct().ToArray()
     79                            // 1 distinct value => skip (constant)
     80                            // 2 distinct values => only take one of the two values
     81                            // >=3 distinct values => create a binary value for each value
     82                            let reducedValues = distinctValues.Length <= 2
     83                              ? distinctValues.Take(distinctValues.Length - 1)
     84                              : distinctValues
     85                            select new KeyValuePair<string, IEnumerable<string>>(factor, reducedValues);
     86      double[,] binaryMatrix = AlglibUtil.PrepareInputMatrix(dataset, factorVariables, rows);
     87      double[,] doubleVarMatrix = AlglibUtil.PrepareInputMatrix(dataset, doubleVariables.Concat(new string[] { targetVariable }), rows);
     88      var inputMatrix = binaryMatrix.VertCat(doubleVarMatrix);
     89
    7690      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
    7791        throw new NotSupportedException("Linear regression does not support NaN or infinity values in the input dataset.");
     
    98112
    99113      int col = 0;
    100       foreach (string column in allowedInputVariables) {
     114      foreach (var kvp in factorVariables) {
     115        var varName = kvp.Key;
     116        foreach (var cat in kvp.Value) {
     117          FactorVariableTreeNode vNode =
     118            (FactorVariableTreeNode)new HeuristicLab.Problems.DataAnalysis.Symbolic.FactorVariable().CreateTreeNode();
     119          vNode.VariableName = varName;
     120          vNode.VariableValue = cat;
     121          vNode.Weight = coefficients[col];
     122          addition.AddSubtree(vNode);
     123          col++;
     124        }
     125      }
     126      foreach (string column in doubleVariables) {
    101127        VariableTreeNode vNode = (VariableTreeNode)new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
    102128        vNode.VariableName = column;
  • branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/Nca/ModelCreation/NcaModelCreator.cs

    r14185 r14237  
    2020#endregion
    2121
     22using System;
    2223using System.Linq;
    2324using HeuristicLab.Common;
  • branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourModel.cs

    r14185 r14237  
    104104      this.allowedInputVariables = allowedInputVariables.ToArray();
    105105
     106      // check input variables. Only double variables are allowed.
     107      var invalidInputs =
     108        allowedInputVariables.Where(name => !dataset.VariableHasType<double>(name));
     109      if (invalidInputs.Any())
     110        throw new NotSupportedException("Gradient tree boosting only supports real-valued variables. Unsupported inputs: " + string.Join(", ", invalidInputs));
     111
     112
    106113      var inputMatrix = AlglibUtil.PrepareInputMatrix(dataset,
    107114                                   allowedInputVariables.Concat(new string[] { targetVariable }),
  • branches/symbreg-factors-2650/HeuristicLab.Common/3.3/MatrixExtensions.cs

    r14185 r14237  
    2020#endregion
    2121
     22using System.Diagnostics.Contracts;
     23
    2224namespace HeuristicLab.Common {
    2325  public static class MatrixExtensions {
     
    3537      return result;
    3638    }
     39
     40    /// <summary>
     41    /// Concatenates matrices horizontally.
     42    /// A      B
     43    /// 1 2    9 8
     44    /// 3 4    7 6
     45    ///
     46    /// HorzCat(A, B)
     47    /// 1 2
     48    /// 3 4
     49    /// 9 8
     50    /// 7 6
     51    /// </summary>
     52    /// <typeparam name="T"></typeparam>
     53    /// <param name="a"></param>
     54    /// <param name="b"></param>
     55    /// <returns>A new matrix with the number of rows = a.GetLength(0) + b.GetLength(0)</returns>
     56    public static T[,] HorzCat<T>(this T[,] a, T[,] b) {
     57      Contract.Assert(a.GetLength(1) == b.GetLength(1));
     58      var aLen = a.GetLength(0);
     59      var bLen = b.GetLength(0);
     60      var result = new T[aLen + bLen, a.GetLength(1)];
     61      for (int i = 0; i < aLen; i++)
     62        for (int j = 0; j < a.GetLength(1); j++)
     63          result[i, j] = a[i, j];
     64      for (int i = 0; i < bLen; i++)
     65        for (int j = 0; j < b.GetLength(1); j++)
     66          result[i + aLen, j] = b[i, j];
     67
     68      return result;
     69    }
     70    /// <summary>
     71    /// Concatenates matrices vertically.
     72    /// A      B
     73    /// 1 2    9 8
     74    /// 3 4    7 6
     75    ///
     76    /// VertCat(A, B)
     77    /// 1 2 9 8
     78    /// 3 4 7 6
     79    /// </summary>
     80    /// <typeparam name="T"></typeparam>
     81    /// <param name="a"></param>
     82    /// <param name="b"></param>
     83    /// <returns>A new matrix with the number of columns = a.GetLength(1) + b.GetLength(1)</returns>
     84    public static T[,] VertCat<T>(this T[,] a, T[,] b) {
     85      Contract.Assert(a.GetLength(0) == b.GetLength(0));
     86      var aLen = a.GetLength(1);
     87      var bLen = b.GetLength(1);
     88      var result = new T[a.GetLength(0), aLen + bLen];
     89      for (int i = 0; i < a.GetLength(0); i++)
     90        for (int j = 0; j < aLen; j++)
     91          result[i, j] = a[i, j];
     92      for (int i = 0; i < a.GetLength(0); i++)
     93        for (int j = 0; j < bLen; j++)
     94          result[i, j + aLen] = b[i, j];
     95      return result;
     96    }
    3797  }
    3898}
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/SymbolicClassificationSolutionImpactValuesCalculator.cs

    r14232 r14237  
    5959      int i = tempModelParentNode.IndexOfSubtree(tempModelNode);
    6060      double bestReplacementValue = 0.0;
    61       double bestImpactValue = double.NegativeInfinity;
     61      double bestImpactValue = double.PositiveInfinity;
    6262      newQualityForImpactsCalculation = qualityForImpactsCalculation; // initialize
    6363      // try the potentially reasonable replacement values and use the best one
     
    7878        impactValue = qualityForImpactsCalculation - newQualityForImpactsCalculation;
    7979
    80         if (impactValue > bestImpactValue) {
     80        if (impactValue < bestImpactValue) {
    8181          bestImpactValue = impactValue;
    8282          bestReplacementValue = repValue;
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs

    r14232 r14237  
    205205          ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
    206206          VariableTreeNode variableTreeNode = node as VariableTreeNode;
     207          FactorVariableTreeNode factorVariableTreeNode = node as FactorVariableTreeNode;
    207208          if (constantTreeNode != null)
    208209            c[i++] = constantTreeNode.Value;
    209210          else if (updateVariableWeights && variableTreeNode != null)
    210211            c[i++] = variableTreeNode.Weight;
     212          else if (updateVariableWeights && factorVariableTreeNode != null)
     213            c[i++] = factorVariableTreeNode.Weight;
    211214        }
    212215      }
     
    270273        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
    271274        VariableTreeNode variableTreeNode = node as VariableTreeNode;
     275        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
    272276        if (constantTreeNode != null)
    273277          constantTreeNode.Value = constants[i++];
    274278        else if (updateVariableWeights && variableTreeNode != null)
    275279          variableTreeNode.Weight = constants[i++];
     280        else if (updateVariableWeights && factorVarTreeNode != null)
     281          factorVarTreeNode.Weight = constants[i++];
    276282      }
    277283    }
     
    299305        return true;
    300306      }
    301       if (node.Symbol is Variable) {
    302         var varNode = node as VariableTreeNode;
     307      if (node.Symbol is Variable || node.Symbol is FactorVariable) {
     308        var varNode = node as VariableTreeNodeBase;
     309        var factorVarNode = node as FactorVariableTreeNode;
     310        // factor variable values are only 0 or 1 and set in x accordingly
    303311        var par = new AutoDiff.Variable();
    304312        parameters.Add(par);
    305313        variableNames.Add(varNode.VariableName);
    306         categoricalVariableValues.Add(string.Empty);   // as a value as placeholder (variableNames.Length == catVariableValues.Length)
     314        categoricalVariableValues.Add(factorVarNode != null ? factorVarNode.VariableValue : string.Empty);
    307315
    308316        if (updateVariableWeights) {
     
    313321          term = par;
    314322        }
    315         return true;
    316       }
    317       if (node.Symbol is FactorVariable) {
    318         // nothing to update in this case (like a variable without a weight)
    319         // values are only 0 or 1 and set in x accordingly
    320         var factorNode = node as FactorVariableTreeNode;
    321         var par = new AutoDiff.Variable();
    322         parameters.Add(par);
    323         variableNames.Add(factorNode.VariableName);
    324         categoricalVariableValues.Add(factorNode.VariableValue);
    325         term = par;
    326323        return true;
    327324      }
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SymbolicRegressionSolutionImpactValuesCalculator.cs

    r14232 r14237  
    6262
    6363      double bestReplacementValue = 0.0;
    64       double bestImpactValue = double.NegativeInfinity;
     64      double bestImpactValue = double.PositiveInfinity;
    6565      newQualityForImpactsCalculation = qualityForImpactsCalculation; // initialize
    6666      // try the potentially reasonable replacement values and use the best one
     
    8080
    8181        impactValue = qualityForImpactsCalculation - newQualityForImpactsCalculation;
    82         if (impactValue > bestImpactValue) {
     82        if (impactValue < bestImpactValue) {
    8383          bestImpactValue = impactValue;
    8484          bestReplacementValue = repValue;
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicExpressionTreeChart.cs

    r14185 r14237  
    200200      // check if the copied/cut node (stored in the tempNode) can be inserted as a child of the current selected node
    201201      var node = currSelected.Content;
    202       if (node is ConstantTreeNode || node is VariableTreeNode) return;
     202      if (node is ConstantTreeNode || node is VariableTreeNodeBase) return;
    203203      // check if the currently selected node can accept the copied node as a child
    204204      // no need to check the grammar, an arity check will do just fine here
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4.csproj

    r14232 r14237  
    200200    <Compile Include="Symbols\FactorVariable.cs" />
    201201    <Compile Include="Symbols\FactorVariableTreeNode.cs" />
     202    <Compile Include="Symbols\VariableBase.cs" />
     203    <Compile Include="Symbols\VariableTreeNodeBase.cs" />
    202204    <Compile Include="Symbols\Xor.cs" />
    203205    <Compile Include="Symbols\Erf.cs" />
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeILEmittingInterpreter.cs

    r14232 r14237  
    639639              il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, varNode.VariableValue);
    640640              il.Emit(System.Reflection.Emit.OpCodes.Call, string_eq);
     641              throw new NotSupportedException();
    641642              // TODO: convert bool to 1 / 0?
    642643            } else {
     
    652653              il.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, varNode.VariableValue);
    653654              il.Emit(System.Reflection.Emit.OpCodes.Call, string_eq);
     655              throw new NotSupportedException();
    654656              // TODO: convert bool to 1 / 0?
    655657              il.Emit(System.Reflection.Emit.OpCodes.Br, normalResult);
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeInterpreter.cs

    r14232 r14237  
    462462            if (row < 0 || row >= dataset.Rows) return double.NaN;
    463463            var factorVarTreeNode = currentInstr.dynamicNode as FactorVariableTreeNode;
    464             return ((IList<string>)currentInstr.data)[row] == factorVarTreeNode.VariableValue ? 1 : 0;
     464            return ((IList<string>)currentInstr.data)[row] == factorVarTreeNode.VariableValue ? factorVarTreeNode.Weight : 0;
    465465          }
    466466        case OpCodes.LagVariable: {
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs

    r14232 r14237  
    152152          else {
    153153            var factorTreeNode = instr.dynamicNode as FactorVariableTreeNode;
    154             instr.value = ((IList<string>)instr.data)[row] == factorTreeNode.VariableValue ? 1 : 0;
     154            instr.value = ((IList<string>)instr.data)[row] == factorTreeNode.VariableValue ? factorTreeNode.Weight : 0;
    155155          }
    156156        } else if (instr.opCode == OpCodes.LagVariable) {
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisExpressionTreeSimplifier.cs

    r14185 r14237  
    833833      var subtrees = new List<ISymbolicExpressionTreeNode>(sum.Subtrees);
    834834      while (sum.Subtrees.Any()) sum.RemoveSubtree(0);
    835       var groupedVarNodes = from node in subtrees.OfType<VariableTreeNode>()
     835      var groupedVarNodes = from node in subtrees.OfType<VariableTreeNodeBase>()
    836836                            let lag = (node is LaggedVariableTreeNode) ? ((LaggedVariableTreeNode)node).Lag : 0
    837837                            group node by node.VariableName + lag into g
    838838                            select g;
    839       var unchangedSubtrees = subtrees.Where(t => !(t is VariableTreeNode));
     839      var unchangedSubtrees = subtrees.Where(t => !(t is VariableTreeNodeBase));
    840840
    841841      foreach (var variableNodeGroup in groupedVarNodes) {
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/FactorVariable.cs

    r14233 r14237  
    4141  [StorableClass]
    4242  [Item("FactorVariable", "Represents a categorical variable (comparable to factors as in R).")]
    43   public class FactorVariable : Symbol {
    44     #region Properties
    45     private List<string> variableNames;
    46     [Storable]
    47     public IEnumerable<string> VariableNames {
    48       get { return variableNames; }
    49       set {
    50         if (value == null) throw new ArgumentNullException();
    51         variableNames.Clear();
    52         variableNames.AddRange(value);
    53         OnChanged(EventArgs.Empty);
    54       }
    55     }
    56 
    57     private List<string> allVariableNames;
    58     [Storable]
    59     public IEnumerable<string> AllVariableNames {
    60       get { return allVariableNames; }
    61       set {
    62         if (value == null) throw new ArgumentNullException();
    63         allVariableNames.Clear();
    64         allVariableNames.AddRange(value);
    65       }
    66     }
     43  public class FactorVariable : VariableBase {
    6744
    6845    private Dictionary<string, List<string>> variableValues;
     
    8057    }
    8158
    82 
    83     public override bool Enabled {
    84       get {
    85         if (variableNames.Count == 0) return false;
    86         return base.Enabled;
    87       }
    88       set {
    89         if (variableNames.Count == 0) base.Enabled = false;
    90         else base.Enabled = value;
    91       }
    92     }
    93 
    94     private const int minimumArity = 0;
    95     private const int maximumArity = 0;
    96 
    97     public override int MinimumArity {
    98       get { return minimumArity; }
    99     }
    100     public override int MaximumArity {
    101       get { return maximumArity; }
    102     }
    103     #endregion
    104 
    10559    [StorableConstructor]
    10660    protected FactorVariable(bool deserializing)
    10761      : base(deserializing) {
    108       variableNames = new List<string>();
    109       allVariableNames = new List<string>();
    11062      variableValues = new Dictionary<string, List<string>>();
    11163    }
    11264    protected FactorVariable(FactorVariable original, Cloner cloner)
    11365      : base(original, cloner) {
    114       variableNames = new List<string>(original.variableNames);
    115       allVariableNames = new List<string>(original.allVariableNames);
    11666      variableValues =
    11767        original.variableValues.ToDictionary(kvp => kvp.Key, kvp => new List<string>(kvp.Value));
     
    12070    public FactorVariable(string name, string description)
    12171      : base(name, description) {
    122       variableNames = new List<string>();
    123       allVariableNames = new List<string>();
    12472      variableValues = new Dictionary<string, List<string>>();
    12573    }
    12674
    127     [StorableHook(HookType.AfterDeserialization)]
    128     private void AfterDeserialization() {
    129       if (allVariableNames == null || (allVariableNames.Count == 0 && variableNames.Count > 0)) {
    130         allVariableNames = variableNames;
    131       }
    132     }
    13375    public override ISymbolicExpressionTreeNode CreateTreeNode() {
    13476      return new FactorVariableTreeNode(this);
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/FactorVariableTreeNode.cs

    r14233 r14237  
    2727namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    2828  [StorableClass]
    29   public class FactorVariableTreeNode : SymbolicExpressionTreeTerminalNode {
     29  public class FactorVariableTreeNode : VariableTreeNodeBase {
    3030    public new FactorVariable Symbol {
    3131      get { return (FactorVariable)base.Symbol; }
    32     }
    33     [Storable]
    34     private string variableName;
    35     public string VariableName {
    36       get { return variableName; }
    37       set { variableName = value; }
    3832    }
    3933
     
    4943    protected FactorVariableTreeNode(FactorVariableTreeNode original, Cloner cloner)
    5044      : base(original, cloner) {
    51       variableName = original.variableName;
    5245      variableValue = original.variableValue;
    5346    }
     
    6154    public override void ResetLocalParameters(IRandom random) {
    6255      base.ResetLocalParameters(random);
    63       variableName = Symbol.VariableNames.SampleRandom(random);
    6456      variableValue = Symbol.GetVariableValues(VariableName).SampleRandom(random);
    6557    }
    6658
    6759    public override void ShakeLocalParameters(IRandom random, double shakingFactor) {
    68       base.ShakeLocalParameters(random, shakingFactor);
     60      // 50% additive & 50% multiplicative
     61      if (random.NextDouble() < 0.5) {
     62        double x = NormalDistributedRandom.NextDouble(random, Symbol.WeightManipulatorMu, Symbol.WeightManipulatorSigma);
     63        Weight = Weight + x * shakingFactor;
     64      } else {
     65        double x = NormalDistributedRandom.NextDouble(random, 1.0, Symbol.MultiplicativeWeightManipulatorSigma);
     66        Weight = Weight * x;
     67      }
    6968      if (random.NextDouble() < 0.2) {
    70         variableName = Symbol.VariableNames.SampleRandom(random);
     69        VariableName = Symbol.VariableNames.SampleRandom(random);
    7170      }
    7271      variableValue = Symbol.GetVariableValues(VariableName).SampleRandom(random);
     
    7877
    7978    public override string ToString() {
    80       return variableName + " = " + variableValue;
     79      return base.ToString() + " = " + variableValue;
    8180    }
    8281  }
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/LaggedVariable.cs

    r14185 r14237  
    2727  [StorableClass]
    2828  [Item("LaggedVariable", "Represents a variable value with a time offset.")]
    29   public class LaggedVariable : Variable {
     29  public class LaggedVariable : VariableBase {
    3030    [Storable]
    3131    private int minLag;
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/LaggedVariableTreeNode.cs

    r14185 r14237  
    2626namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    2727  [StorableClass]
    28   public sealed class LaggedVariableTreeNode : VariableTreeNode, ILaggedTreeNode {
     28  public sealed class LaggedVariableTreeNode : VariableTreeNodeBase, ILaggedTreeNode {
    2929    public new LaggedVariable Symbol {
    3030      get { return (LaggedVariable)base.Symbol; }
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/Variable.cs

    r14185 r14237  
    2929  [StorableClass]
    3030  [Item("Variable", "Represents a variable value.")]
    31   public class Variable : Symbol {
    32     #region Properties
    33     [Storable]
    34     private double weightMu;
    35     public double WeightMu {
    36       get { return weightMu; }
    37       set {
    38         if (value != weightMu) {
    39           weightMu = value;
    40           OnChanged(EventArgs.Empty);
    41         }
    42       }
    43     }
    44     [Storable]
    45     private double weightSigma;
    46     public double WeightSigma {
    47       get { return weightSigma; }
    48       set {
    49         if (weightSigma < 0.0) throw new ArgumentException("Negative sigma is not allowed.");
    50         if (value != weightSigma) {
    51           weightSigma = value;
    52           OnChanged(EventArgs.Empty);
    53         }
    54       }
    55     }
    56     [Storable]
    57     private double weightManipulatorMu;
    58     public double WeightManipulatorMu {
    59       get { return weightManipulatorMu; }
    60       set {
    61         if (value != weightManipulatorMu) {
    62           weightManipulatorMu = value;
    63           OnChanged(EventArgs.Empty);
    64         }
    65       }
    66     }
    67     [Storable]
    68     private double weightManipulatorSigma;
    69     public double WeightManipulatorSigma {
    70       get { return weightManipulatorSigma; }
    71       set {
    72         if (weightManipulatorSigma < 0.0) throw new ArgumentException("Negative sigma is not allowed.");
    73         if (value != weightManipulatorSigma) {
    74           weightManipulatorSigma = value;
    75           OnChanged(EventArgs.Empty);
    76         }
    77       }
    78     }
    79     [Storable(DefaultValue = 0.0)]
    80     private double multiplicativeWeightManipulatorSigma;
    81     public double MultiplicativeWeightManipulatorSigma {
    82       get { return multiplicativeWeightManipulatorSigma; }
    83       set {
    84         if (multiplicativeWeightManipulatorSigma < 0.0) throw new ArgumentException("Negative sigma is not allowed.");
    85         if (value != multiplicativeWeightManipulatorSigma) {
    86           multiplicativeWeightManipulatorSigma = value;
    87           OnChanged(EventArgs.Empty);
    88         }
    89       }
    90     }
    91     private List<string> variableNames;
    92     [Storable]
    93     public IEnumerable<string> VariableNames {
    94       get { return variableNames; }
    95       set {
    96         if (value == null) throw new ArgumentNullException();
    97         variableNames.Clear();
    98         variableNames.AddRange(value);
    99         OnChanged(EventArgs.Empty);
    100       }
    101     }
    102 
    103     private List<string> allVariableNames;
    104     [Storable]
    105     public IEnumerable<string> AllVariableNames {
    106       get { return allVariableNames; }
    107       set {
    108         if (value == null) throw new ArgumentNullException();
    109         allVariableNames.Clear();
    110         allVariableNames.AddRange(value);
    111       }
    112     }
    113 
    114     public override bool Enabled {
    115       get {
    116         if (variableNames.Count == 0) return false;
    117         return base.Enabled;
    118       }
    119       set {
    120         if (variableNames.Count == 0) base.Enabled = false;
    121         else base.Enabled = value;
    122       }
    123     }
    124 
    125     private const int minimumArity = 0;
    126     private const int maximumArity = 0;
    127 
    128     public override int MinimumArity {
    129       get { return minimumArity; }
    130     }
    131     public override int MaximumArity {
    132       get { return maximumArity; }
    133     }
    134     #endregion
    135 
    136     [StorableHook(HookType.AfterDeserialization)]
    137     private void AfterDeserialization() {
    138       if (allVariableNames == null || (allVariableNames.Count == 0 && variableNames.Count > 0)) {
    139         allVariableNames = variableNames;
    140       }
    141     }
     31  public class Variable : VariableBase {
    14232
    14333    [StorableConstructor]
    14434    protected Variable(bool deserializing)
    14535      : base(deserializing) {
    146       variableNames = new List<string>();
    147       allVariableNames = new List<string>();
    14836    }
    14937    protected Variable(Variable original, Cloner cloner)
    15038      : base(original, cloner) {
    151       weightMu = original.weightMu;
    152       weightSigma = original.weightSigma;
    153       variableNames = new List<string>(original.variableNames);
    154       allVariableNames = new List<string>(original.allVariableNames);
    155       weightManipulatorMu = original.weightManipulatorMu;
    156       weightManipulatorSigma = original.weightManipulatorSigma;
    157       multiplicativeWeightManipulatorSigma = original.multiplicativeWeightManipulatorSigma;
    15839    }
    159     public Variable() : this("Variable", "Represents a variable value.") { }
    160     public Variable(string name, string description)
    161       : base(name, description) {
    162       weightMu = 1.0;
    163       weightSigma = 1.0;
    164       weightManipulatorMu = 0.0;
    165       weightManipulatorSigma = 0.05;
    166       multiplicativeWeightManipulatorSigma = 0.03;
    167       variableNames = new List<string>();
    168       allVariableNames = new List<string>();
    169     }
     40    public Variable() : base("Variable", "Represents a variable value.") { }
    17041
    17142    public override ISymbolicExpressionTreeNode CreateTreeNode() {
  • branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Symbols/VariableTreeNode.cs

    r14185 r14237  
    2121
    2222using HeuristicLab.Common;
    23 using HeuristicLab.Core;
    24 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2523using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    26 using HeuristicLab.Random;
    2724namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    2825  [StorableClass]
    29   public class VariableTreeNode : SymbolicExpressionTreeTerminalNode {
     26  public class VariableTreeNode : VariableTreeNodeBase {
    3027    public new Variable Symbol {
    3128      get { return (Variable)base.Symbol; }
    3229    }
    33     [Storable]
    34     private double weight;
    35     public double Weight {
    36       get { return weight; }
    37       set { weight = value; }
    38     }
    39     [Storable]
    40     private string variableName;
    41     public string VariableName {
    42       get { return variableName; }
    43       set { variableName = value; }
    44     }
    45 
    4630    [StorableConstructor]
    4731    protected VariableTreeNode(bool deserializing) : base(deserializing) { }
    4832    protected VariableTreeNode(VariableTreeNode original, Cloner cloner)
    4933      : base(original, cloner) {
    50       weight = original.weight;
    51       variableName = original.variableName;
    5234    }
    5335    protected VariableTreeNode() { }
    5436    public VariableTreeNode(Variable variableSymbol) : base(variableSymbol) { }
    5537
    56     public override bool HasLocalParameters {
    57       get { return true; }
    58     }
    59 
    60     public override void ResetLocalParameters(IRandom random) {
    61       base.ResetLocalParameters(random);
    62       weight = NormalDistributedRandom.NextDouble(random, Symbol.WeightMu, Symbol.WeightSigma);
    63 
    64 #pragma warning disable 612, 618
    65       variableName = Symbol.VariableNames.SelectRandom(random);
    66 #pragma warning restore 612, 618
    67     }
    68 
    69     public override void ShakeLocalParameters(IRandom random, double shakingFactor) {
    70       base.ShakeLocalParameters(random, shakingFactor);
    71       // 50% additive & 50% multiplicative
    72       if (random.NextDouble() < 0) {
    73         double x = NormalDistributedRandom.NextDouble(random, Symbol.WeightManipulatorMu, Symbol.WeightManipulatorSigma);
    74         weight = weight + x * shakingFactor;
    75       } else {
    76         double x = NormalDistributedRandom.NextDouble(random, 1.0, Symbol.MultiplicativeWeightManipulatorSigma);
    77         weight = weight * x;
    78       }
    79 #pragma warning disable 612, 618
    80       variableName = Symbol.VariableNames.SelectRandom(random);
    81 #pragma warning restore 612, 618
    82     }
    83 
    8438    public override IDeepCloneable Clone(Cloner cloner) {
    8539      return new VariableTreeNode(this, cloner);
    8640    }
    87 
    88     public override string ToString() {
    89       if (weight.IsAlmost(1.0)) return variableName;
    90       else return weight.ToString("E4") + " " + variableName;
    91     }
    9241  }
    9342}
Note: See TracChangeset for help on using the changeset viewer.