Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
09/08/16 11:41:45 (8 years ago)
Author:
gkronber
Message:

#2650: merged r14245:14273 from trunk to branch (fixing conflicts in RegressionSolutionTargetResponseGradientView)

File:
1 edited

Legend:

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

    r14251 r14277  
    3232using HeuristicLab.Problems.DataAnalysis.Symbolic;
    3333using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
     34using HeuristicLab.Random;
    3435
    3536namespace HeuristicLab.Algorithms.DataAnalysis {
     
    4445    private const string ModelStructureParameterName = "Model structure";
    4546    private const string IterationsParameterName = "Iterations";
     47    private const string RestartsParameterName = "Restarts";
     48    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
     49    private const string SeedParameterName = "Seed";
    4650
    4751    public IFixedValueParameter<StringValue> ModelStructureParameter {
     
    5054    public IFixedValueParameter<IntValue> IterationsParameter {
    5155      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
     56    }
     57
     58    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
     59      get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
     60    }
     61
     62    public IFixedValueParameter<IntValue> SeedParameter {
     63      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
     64    }
     65
     66    public IFixedValueParameter<IntValue> RestartsParameter {
     67      get { return (IFixedValueParameter<IntValue>)Parameters[RestartsParameterName]; }
    5268    }
    5369
     
    6278    }
    6379
     80    public int Restarts {
     81      get { return RestartsParameter.Value.Value; }
     82      set { RestartsParameter.Value.Value = value; }
     83    }
     84
     85    public int Seed {
     86      get { return SeedParameter.Value.Value; }
     87      set { SeedParameter.Value.Value = value; }
     88    }
     89
     90    public bool SetSeedRandomly {
     91      get { return SetSeedRandomlyParameter.Value.Value; }
     92      set { SetSeedRandomlyParameter.Value.Value = value; }
     93    }
    6494
    6595    [StorableConstructor]
     
    73103      Parameters.Add(new FixedValueParameter<StringValue>(ModelStructureParameterName, "The function for which the parameters must be fit (only numeric constants are tuned).", new StringValue("1.0 * x*x + 0.0")));
    74104      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200)));
    75     }
     105      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts", new IntValue(10)));
     106      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
     107      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
     108    }
     109
    76110    [StorableHook(HookType.AfterDeserialization)]
    77     private void AfterDeserialization() { }
     111    private void AfterDeserialization() {
     112      // BackwardsCompatibility3.3
     113      #region Backwards compatible code, remove with 3.4
     114      if (!Parameters.ContainsKey(RestartsParameterName))
     115        Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts", new IntValue(1)));
     116      if (!Parameters.ContainsKey(SeedParameterName))
     117        Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
     118      if (!Parameters.ContainsKey(SetSeedRandomlyParameterName))
     119        Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
     120      #endregion
     121    }
    78122
    79123    public override IDeepCloneable Clone(Cloner cloner) {
     
    83127    #region nonlinear regression
    84128    protected override void Run() {
    85       var solution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations);
    86       Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", solution));
    87       Results.Add(new Result("Root mean square error (train)", "The root of the mean of squared errors of the regression solution on the training set.", new DoubleValue(solution.TrainingRootMeanSquaredError)));
    88       Results.Add(new Result("Root mean square error (test)", "The root of the mean of squared errors of the regression solution on the test set.", new DoubleValue(solution.TestRootMeanSquaredError)));
    89     }
    90 
    91     public static ISymbolicRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData, string modelStructure, int maxIterations) {
     129      if (SetSeedRandomly) Seed = (new System.Random()).Next();
     130      var rand = new MersenneTwister((uint)Seed);
     131      IRegressionSolution bestSolution = null;
     132      for (int r = 0; r < Restarts; r++) {
     133        var solution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, rand);
     134        if (bestSolution == null || solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
     135          bestSolution = solution;
     136        }
     137      }
     138
     139      Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution));
     140      Results.Add(new Result("Root mean square error (train)", "The root of the mean of squared errors of the regression solution on the training set.", new DoubleValue(bestSolution.TrainingRootMeanSquaredError)));
     141      Results.Add(new Result("Root mean square error (test)", "The root of the mean of squared errors of the regression solution on the test set.", new DoubleValue(bestSolution.TestRootMeanSquaredError)));
     142
     143    }
     144
     145    /// <summary>
     146    /// Fits a model to the data by optimizing the numeric constants.
     147    /// Model is specified as infix expression containing variable names and numbers.
     148    /// The starting point for the numeric constants is initialized randomly if a random number generator is specified (~N(0,1)). Otherwise the user specified constants are
     149    /// used as a starting point.
     150    /// </summary>
     151    /// <param name="problemData">Training and test data</param>
     152    /// <param name="modelStructure">The function as infix expression</param>
     153    /// <param name="maxIterations">Number of constant optimization iterations (using Levenberg-Marquardt algorithm)</param>
     154    /// <param name="random">Optional random number generator for random initialization of numeric constants.</param>
     155    /// <returns></returns>
     156    public static ISymbolicRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData, string modelStructure, int maxIterations, IRandom random = null) {
    92157      var parser = new InfixExpressionParser();
    93158      var tree = parser.Parse(modelStructure);
     
    117182      if (!SymbolicRegressionConstantOptimizationEvaluator.CanOptimizeConstants(tree)) throw new ArgumentException("The optimizer does not support the specified model structure.");
    118183
     184      // initialize constants randomly
     185      if (random != null) {
     186        foreach (var node in tree.IterateNodesPrefix().OfType<ConstantTreeNode>()) {
     187          node.Value = NormalDistributedRandom.NextDouble(random, 0, 1);
     188        }
     189      }
    119190      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
     191
    120192      SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, problemData.TrainingIndices,
    121193        applyLinearScaling: false, maxIterations: maxIterations,
    122194        updateVariableWeights: false, updateConstantsInTree: true);
    123 
    124195
    125196      var scaledModel = new SymbolicRegressionModel(problemData.TargetVariable, tree, (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter.Clone());
Note: See TracChangeset for help on using the changeset viewer.