#region License Information /* HeuristicLab * Copyright (C) 2002-2019 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; using System.Collections.Generic; using System.Linq; using System.Threading; using HeuristicLab.Analysis; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.Optimization; using HeuristicLab.Parameters; using HEAL.Attic; using HeuristicLab.Problems.DataAnalysis; using HeuristicLab.Problems.DataAnalysis.Symbolic; using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression; using HeuristicLab.Random; using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; namespace HeuristicLab.Algorithms.DataAnalysis { /// /// Nonlinear regression data analysis algorithm. /// [Item("Nonlinear Regression with Constraints (NLR)", "Nonlinear regression (curve fitting) data analysis algorithm that supports interval constraints.")] [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 120)] [StorableType("B235DB6E-591F-4537-8D2F-C2D1232AAEFD")] public sealed class ConstrainedNonlinearRegression : FixedDataAnalysisAlgorithm { private const string RegressionSolutionResultName = "Regression solution"; private const string ModelStructureParameterName = "Model structure"; private const string IterationsParameterName = "Iterations"; private const string RestartsParameterName = "Restarts"; private const string SetSeedRandomlyParameterName = "SetSeedRandomly"; private const string SeedParameterName = "Seed"; private const string InitParamsRandomlyParameterName = "InitializeParametersRandomly"; private const string ApplyLinearScalingParameterName = "Apply linear scaling"; public IFixedValueParameter ModelStructureParameter { get { return (IFixedValueParameter)Parameters[ModelStructureParameterName]; } } public IFixedValueParameter IterationsParameter { get { return (IFixedValueParameter)Parameters[IterationsParameterName]; } } public IFixedValueParameter SetSeedRandomlyParameter { get { return (IFixedValueParameter)Parameters[SetSeedRandomlyParameterName]; } } public IFixedValueParameter SeedParameter { get { return (IFixedValueParameter)Parameters[SeedParameterName]; } } public IFixedValueParameter RestartsParameter { get { return (IFixedValueParameter)Parameters[RestartsParameterName]; } } public IFixedValueParameter InitParametersRandomlyParameter { get { return (IFixedValueParameter)Parameters[InitParamsRandomlyParameterName]; } } public IFixedValueParameter ApplyLinearScalingParameter { get { return (IFixedValueParameter)Parameters[ApplyLinearScalingParameterName]; } } public string ModelStructure { get { return ModelStructureParameter.Value.Value; } set { ModelStructureParameter.Value.Value = value; } } public int Iterations { get { return IterationsParameter.Value.Value; } set { IterationsParameter.Value.Value = value; } } public int Restarts { get { return RestartsParameter.Value.Value; } set { RestartsParameter.Value.Value = value; } } public int Seed { get { return SeedParameter.Value.Value; } set { SeedParameter.Value.Value = value; } } public bool SetSeedRandomly { get { return SetSeedRandomlyParameter.Value.Value; } set { SetSeedRandomlyParameter.Value.Value = value; } } public bool InitializeParametersRandomly { get { return InitParametersRandomlyParameter.Value.Value; } set { InitParametersRandomlyParameter.Value.Value = value; } } public bool ApplyLinearScaling { get { return ApplyLinearScalingParameter.Value.Value; } set { ApplyLinearScalingParameter.Value.Value = value; } } [StorableConstructor] private ConstrainedNonlinearRegression(StorableConstructorFlag _) : base(_) { } private ConstrainedNonlinearRegression(ConstrainedNonlinearRegression original, Cloner cloner) : base(original, cloner) { } public ConstrainedNonlinearRegression() : base() { Problem = new RegressionProblem(); Parameters.Add(new FixedValueParameter(ModelStructureParameterName, "The function for which the parameters must be fit (only numeric constants are tuned).", new StringValue("1.0 * x*x + 0.0"))); Parameters.Add(new FixedValueParameter(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200))); Parameters.Add(new FixedValueParameter(RestartsParameterName, "The number of independent random restarts (>0)", new IntValue(10))); Parameters.Add(new FixedValueParameter(SeedParameterName, "The PRNG seed value.", new IntValue())); Parameters.Add(new FixedValueParameter(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true))); Parameters.Add(new FixedValueParameter(InitParamsRandomlyParameterName, "Switch to determine if the real-valued model parameters should be initialized randomly in each restart.", new BoolValue(false))); Parameters.Add(new FixedValueParameter(ApplyLinearScalingParameterName, "Switch to determine if linear scaling terms should be added to the model", new BoolValue(true))); SetParameterHiddenState(); InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => { SetParameterHiddenState(); }; } private void SetParameterHiddenState() { var hide = !InitializeParametersRandomly; RestartsParameter.Hidden = hide; SeedParameter.Hidden = hide; SetSeedRandomlyParameter.Hidden = hide; } [StorableHook(HookType.AfterDeserialization)] private void AfterDeserialization() { SetParameterHiddenState(); InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => { SetParameterHiddenState(); }; } public override IDeepCloneable Clone(Cloner cloner) { return new ConstrainedNonlinearRegression(this, cloner); } #region nonlinear regression protected override void Run(CancellationToken cancellationToken) { IRegressionSolution bestSolution = null; if (InitializeParametersRandomly) { var qualityTable = new DataTable("RMSE table"); qualityTable.VisualProperties.YAxisLogScale = true; var trainRMSERow = new DataRow("RMSE (train)"); trainRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points; var testRMSERow = new DataRow("RMSE test"); testRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points; qualityTable.Rows.Add(trainRMSERow); qualityTable.Rows.Add(testRMSERow); Results.Add(new Result(qualityTable.Name, qualityTable.Name + " for all restarts", qualityTable)); if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed(); var rand = new MersenneTwister((uint)Seed); bestSolution = CreateRegressionSolution((RegressionProblemData)Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling, rand); trainRMSERow.Values.Add(bestSolution.TrainingRootMeanSquaredError); testRMSERow.Values.Add(bestSolution.TestRootMeanSquaredError); for (int r = 0; r < Restarts; r++) { var solution = CreateRegressionSolution((RegressionProblemData)Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling, rand); trainRMSERow.Values.Add(solution.TrainingRootMeanSquaredError); testRMSERow.Values.Add(solution.TestRootMeanSquaredError); if (solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) { bestSolution = solution; } } } else { bestSolution = CreateRegressionSolution((RegressionProblemData)Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling); } Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution)); 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))); 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))); } /// /// Fits a model to the data by optimizing the numeric constants. /// Model is specified as infix expression containing variable names and numbers. /// 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 /// used as a starting point. /// - /// Training and test data /// The function as infix expression /// Number of constant optimization iterations (using Levenberg-Marquardt algorithm) /// Optional random number generator for random initialization of numeric constants. /// public static ISymbolicRegressionSolution CreateRegressionSolution(RegressionProblemData problemData, string modelStructure, int maxIterations, bool applyLinearScaling, IRandom rand = null) { if (applyLinearScaling) throw new NotSupportedException("Linear scaling is not yet supported in NLR with constraints."); var parser = new InfixExpressionParser(); var tree = parser.Parse(modelStructure); // parser handles double and string variables equally by creating a VariableTreeNode // post-process to replace VariableTreeNodes by FactorVariableTreeNodes for all string variables var factorSymbol = new FactorVariable(); factorSymbol.VariableNames = problemData.AllowedInputVariables.Where(name => problemData.Dataset.VariableHasType(name)); factorSymbol.AllVariableNames = factorSymbol.VariableNames; factorSymbol.VariableValues = factorSymbol.VariableNames.Select(name => new KeyValuePair>(name, problemData.Dataset.GetReadOnlyStringValues(name).Distinct() .Select((n, i) => Tuple.Create(n, i)) .ToDictionary(tup => tup.Item1, tup => tup.Item2))); foreach (var parent in tree.IterateNodesPrefix().ToArray()) { for (int i = 0; i < parent.SubtreeCount; i++) { var varChild = parent.GetSubtree(i) as VariableTreeNode; var factorVarChild = parent.GetSubtree(i) as FactorVariableTreeNode; if (varChild != null && factorSymbol.VariableNames.Contains(varChild.VariableName)) { parent.RemoveSubtree(i); var factorTreeNode = (FactorVariableTreeNode)factorSymbol.CreateTreeNode(); factorTreeNode.VariableName = varChild.VariableName; factorTreeNode.Weights = factorTreeNode.Symbol.GetVariableValues(factorTreeNode.VariableName).Select(_ => 1.0).ToArray(); // weight = 1.0 for each value parent.InsertSubtree(i, factorTreeNode); } else if (factorVarChild != null && factorSymbol.VariableNames.Contains(factorVarChild.VariableName)) { if (factorSymbol.GetVariableValues(factorVarChild.VariableName).Count() != factorVarChild.Weights.Length) throw new ArgumentException( string.Format("Factor variable {0} needs exactly {1} weights", factorVarChild.VariableName, factorSymbol.GetVariableValues(factorVarChild.VariableName).Count())); parent.RemoveSubtree(i); var factorTreeNode = (FactorVariableTreeNode)factorSymbol.CreateTreeNode(); factorTreeNode.VariableName = factorVarChild.VariableName; factorTreeNode.Weights = factorVarChild.Weights; parent.InsertSubtree(i, factorTreeNode); } } } var intervalConstraints = problemData.IntervalConstraints; var dataIntervals = problemData.VariableRanges.GetIntervals(); // convert constants to variables named theta... var treeForDerivation = ReplaceConstWithVar(tree, out List thetaNames, out List thetaValues); // create trees for relevant derivatives Dictionary derivatives = new Dictionary(); var allThetaNodes = thetaNames.Select(_ => new List()).ToArray(); var constraintTrees = new List(); foreach (var constraint in intervalConstraints.Constraints) { if (constraint.IsDerivation) { if (!problemData.AllowedInputVariables.Contains(constraint.Variable)) throw new ArgumentException($"Invalid constraint: the variable {constraint.Variable} does not exist in the dataset."); var df = DerivativeCalculator.Derive(treeForDerivation, constraint.Variable); // alglib requires constraint expressions of the form c(x) <= 0 // -> we make two expressions, one for the lower bound and one for the upper bound if (constraint.Interval.UpperBound < double.PositiveInfinity) { var df_smaller_upper = Subtract((ISymbolicExpressionTree)df.Clone(), CreateConstant(constraint.Interval.UpperBound)); // convert variables named theta back to constants var df_prepared = ReplaceVarWithConst(df_smaller_upper, thetaNames, thetaValues, allThetaNodes); constraintTrees.Add(df_prepared); } if (constraint.Interval.LowerBound > double.NegativeInfinity) { var df_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)df.Clone()); // convert variables named theta back to constants var df_prepared = ReplaceVarWithConst(df_larger_lower, thetaNames, thetaValues, allThetaNodes); constraintTrees.Add(df_prepared); } } else { if (constraint.Interval.UpperBound < double.PositiveInfinity) { var f_smaller_upper = Subtract((ISymbolicExpressionTree)treeForDerivation.Clone(), CreateConstant(constraint.Interval.UpperBound)); // convert variables named theta back to constants var df_prepared = ReplaceVarWithConst(f_smaller_upper, thetaNames, thetaValues, allThetaNodes); constraintTrees.Add(df_prepared); } if (constraint.Interval.LowerBound > double.NegativeInfinity) { var f_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)treeForDerivation.Clone()); // convert variables named theta back to constants var df_prepared = ReplaceVarWithConst(f_larger_lower, thetaNames, thetaValues, allThetaNodes); constraintTrees.Add(df_prepared); } } } var preparedTree = ReplaceVarWithConst(treeForDerivation, thetaNames, thetaValues, allThetaNodes); // initialize constants randomly if (rand != null) { for (int i = 0; i < allThetaNodes.Length; i++) { double f = Math.Exp(NormalDistributedRandom.NextDouble(rand, 0, 1)); double scale = rand.NextDouble() < 0.5 ? -1 : 1; thetaValues[i] = scale * thetaValues[i] * f; foreach (var constNode in allThetaNodes[i]) constNode.Value = thetaValues[i]; } } // local function void UpdateThetaValues(double[] theta) { for (int i = 0; i < theta.Length; ++i) { foreach (var constNode in allThetaNodes[i]) constNode.Value = theta[i]; } } // buffers for calculate_jacobian var target = problemData.TargetVariableTrainingValues.ToArray(); var fi_eval = new double[target.Length]; var jac_eval = new double[target.Length, thetaValues.Count]; // define the callback used by the alglib optimizer // the x argument for this callback represents our theta // local function void calculate_jacobian(double[] x, double[] fi, double[,] jac, object obj) { UpdateThetaValues(x); var autoDiffEval = new VectorAutoDiffEvaluator(); autoDiffEval.Evaluate(preparedTree, problemData.Dataset, problemData.TrainingIndices.ToArray(), GetParameterNodes(preparedTree, allThetaNodes), fi_eval, jac_eval); // calc sum of squared errors and gradient var sse = 0.0; var g = new double[x.Length]; for (int i = 0; i < target.Length; i++) { var res = target[i] - fi_eval[i]; sse += 0.5 * res * res; for (int j = 0; j < g.Length; j++) { g[j] -= res * jac_eval[i, j]; } } fi[0] = sse / target.Length; for (int j = 0; j < x.Length; j++) { jac[0, j] = g[j] / target.Length; } var intervalEvaluator = new IntervalEvaluator(); for (int i = 0; i < constraintTrees.Count; i++) { var interval = intervalEvaluator.Evaluate(constraintTrees[i], dataIntervals, GetParameterNodes(constraintTrees[i], allThetaNodes), out double[] lowerGradient, out double[] upperGradient); // we transformed this to a constraint c(x) <= 0, so only the upper bound is relevant for us fi[i + 1] = interval.UpperBound; for (int j = 0; j < x.Length; j++) { jac[i + 1, j] = upperGradient[j]; } } } // prepare alglib alglib.minnlcstate state; alglib.minnlcreport rep; //alglib.optguardreport optGuardRep; var x0 = thetaValues.ToArray(); alglib.minnlccreate(x0.Length, x0, out state); alglib.minnlcsetalgoslp(state); // SLP is more robust but slower alglib.minnlcsetcond(state, 1E-6, maxIterations); var s = Enumerable.Repeat(1d, x0.Length).ToArray(); // scale is set to unit scale alglib.minnlcsetscale(state, s); // set non-linear constraints: 0 equality constraints, 1 inequality constraint alglib.minnlcsetnlc(state, 0, constraintTrees.Count); // alglib.minnlcoptguardsmoothness(state); // alglib.minnlcoptguardgradient(state, 0.001); alglib.minnlcoptimize(state, calculate_jacobian, null, null); alglib.minnlcresults(state, out double[] xOpt, out rep); // alglib.minnlcoptguardresults(state, out optGuardRep); var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter(); UpdateThetaValues(xOpt); var model = new SymbolicRegressionModel(problemData.TargetVariable, (ISymbolicExpressionTree)preparedTree.Clone(), (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter.Clone()); if (applyLinearScaling) model.Scale(problemData); SymbolicRegressionSolution solution = new SymbolicRegressionSolution(model, (IRegressionProblemData)problemData.Clone()); solution.Model.Name = "Regression Model"; solution.Name = "Regression Solution"; return solution; } private static ISymbolicExpressionTreeNode[] GetParameterNodes(ISymbolicExpressionTree tree, List[] allNodes) { // TODO better solution necessary var treeConstNodes = tree.IterateNodesPostfix().OfType().ToArray(); var paramNodes = new ISymbolicExpressionTreeNode[allNodes.Length]; for (int i = 0; i < paramNodes.Length; i++) { paramNodes[i] = allNodes[i].SingleOrDefault(n => treeConstNodes.Contains(n)); } return paramNodes; } #endregion #region helper private static ISymbolicExpressionTree ReplaceVarWithConst(ISymbolicExpressionTree tree, List thetaNames, List thetaValues, List[] thetaNodes) { var copy = (ISymbolicExpressionTree)tree.Clone(); var nodes = copy.IterateNodesPostfix().ToList(); for (int i = 0; i < nodes.Count; i++) { var n = nodes[i] as VariableTreeNode; if (n != null) { var thetaIdx = thetaNames.IndexOf(n.VariableName); if (thetaIdx >= 0) { var parent = n.Parent; if (thetaNodes[thetaIdx].Any()) { // HACK: REUSE CONSTANT TREE NODE IN SEVERAL TREES // we use this trick to allow autodiff over thetas when thetas occurr multiple times in the tree (e.g. in derived trees) var constNode = thetaNodes[thetaIdx].First(); var childIdx = parent.IndexOfSubtree(n); parent.RemoveSubtree(childIdx); parent.InsertSubtree(childIdx, constNode); } else { var constNode = (ConstantTreeNode)CreateConstant(thetaValues[thetaIdx]); var childIdx = parent.IndexOfSubtree(n); parent.RemoveSubtree(childIdx); parent.InsertSubtree(childIdx, constNode); thetaNodes[thetaIdx].Add(constNode); } } } } return copy; } private static ISymbolicExpressionTree ReplaceConstWithVar(ISymbolicExpressionTree tree, out List thetaNames, out List thetaValues) { thetaNames = new List(); thetaValues = new List(); var copy = (ISymbolicExpressionTree)tree.Clone(); var nodes = copy.IterateNodesPostfix().ToList(); int n = 1; for (int i = 0; i < nodes.Count; ++i) { var node = nodes[i]; if (node is ConstantTreeNode constantTreeNode) { var thetaVar = (VariableTreeNode)new Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode(); thetaVar.Weight = 1; thetaVar.VariableName = $"θ{n++}"; thetaNames.Add(thetaVar.VariableName); thetaValues.Add(constantTreeNode.Value); var parent = constantTreeNode.Parent; if (parent != null) { var index = constantTreeNode.Parent.IndexOfSubtree(constantTreeNode); parent.RemoveSubtree(index); parent.InsertSubtree(index, thetaVar); } } } return copy; } private static ISymbolicExpressionTreeNode CreateConstant(double value) { var constantNode = (ConstantTreeNode)new Constant().CreateTreeNode(); constantNode.Value = value; return constantNode; } private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTree t, ISymbolicExpressionTreeNode b) { var sub = MakeNode(t.Root.GetSubtree(0).GetSubtree(0), b); t.Root.GetSubtree(0).RemoveSubtree(0); t.Root.GetSubtree(0).InsertSubtree(0, sub); return t; } private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTreeNode b, ISymbolicExpressionTree t) { var sub = MakeNode(b, t.Root.GetSubtree(0).GetSubtree(0)); t.Root.GetSubtree(0).RemoveSubtree(0); t.Root.GetSubtree(0).InsertSubtree(0, sub); return t; } private static ISymbolicExpressionTreeNode MakeNode(params ISymbolicExpressionTreeNode[] fs) where T : ISymbol, new() { var node = new T().CreateTreeNode(); foreach (var f in fs) node.AddSubtree(f); return node; } #endregion } }