.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_meta_modeling/kriging_metamodel/plot_kriging_hyperparameters_optimization.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_meta_modeling_kriging_metamodel_plot_kriging_hyperparameters_optimization.py: Kriging :configure the optimization solver ========================================== .. GENERATED FROM PYTHON SOURCE LINES 6-33 The goal of this example is to show how to fine-tune the optimization solver used to estimate the hyperparameters of the covariance model of the kriging metamodel. Introduction ------------ In a kriging metamodel, there are various types of parameters which are estimated from the data. * The parameters :math:`{\bf \beta}` associated with the deterministic trend. These parameters are computed based on linear least squares. * The parameters of the covariance model. The covariance model has two types of parameters. * The amplitude parameter :math:`\sigma^2` is estimated from the data. If the output dimension is equal to one, this parameter is estimated using the analytic variance estimator which maximizes the likelihood. Otherwise, if output dimension is greater than one or analytical sigma disabled, this parameter is estimated from numerical optimization. * The other parameters :math:`{\bf \theta}\in\mathbb{R}^d` where :math:`d` is the spatial dimension of the covariance model. Often, the parameter :math:`{\bf \theta}` is a scale parameter. This step involves an optimization algorithm. All these parameters are estimated with the `GeneralLinearModelAlgorithm` class. The estimation of the :math:`{\bf \theta}` parameters is the step which has the highest CPU cost. Moreover, the maximization of likelihood may be associated with difficulties e.g. many local maximums or even the non convergence of the optimization algorithm. In this case, it might be useful to fine tune the optimization algorithm so that the convergence of the optimization algorithm is, hopefully, improved. Furthermore, there are several situations in which the optimization can be initialized or completely bypassed. Suppose for example that we have already created an initial kriging metamodel with :math:`N` points and we want to add a single new point. * It might be interesting to initialize the optimization algorithm with the optimum found for the previous kriging metamodel: this may reduce the number of iterations required to maximize the likelihood. * We may as well completely bypass the optimization step: if the previous covariance model was correctly estimated, the update of the parameters may or may not significantly improve the estimates. This is why the goal of this example is to see how to configure the optimization of the hyperparameters of a kriging metamodel. .. GENERATED FROM PYTHON SOURCE LINES 35-37 Definition of the model ----------------------- .. GENERATED FROM PYTHON SOURCE LINES 39-43 .. code-block:: default import openturns as ot ot.Log.Show(ot.Log.NONE) .. GENERATED FROM PYTHON SOURCE LINES 44-45 We define the symbolic function which evaluates the output Y depending on the inputs E, F, L and I. .. GENERATED FROM PYTHON SOURCE LINES 47-49 .. code-block:: default model = ot.SymbolicFunction(["E", "F", "L", "I"], ["F*L^3/(3*E*I)"]) .. GENERATED FROM PYTHON SOURCE LINES 50-51 Then we define the distribution of the input random vector. .. GENERATED FROM PYTHON SOURCE LINES 53-54 Young's modulus E .. GENERATED FROM PYTHON SOURCE LINES 54-67 .. code-block:: default E = ot.Beta(0.9, 2.27, 2.5e7, 5.0e7) # in N/m^2 E.setDescription("E") # Load F F = ot.LogNormal() # in N F.setParameter(ot.LogNormalMuSigma()([30.0e3, 9e3, 15.0e3])) F.setDescription("F") # Length L L = ot.Uniform(250.0, 260.0) # in cm L.setDescription("L") # Moment of inertia I II = ot.Beta(2.5, 1.5, 310, 450) # in cm^4 II.setDescription("I") .. GENERATED FROM PYTHON SOURCE LINES 68-69 Finally, we define the dependency using a `NormalCopula`. .. GENERATED FROM PYTHON SOURCE LINES 71-77 .. code-block:: default dim = 4 # number of inputs R = ot.CorrelationMatrix(dim) R[2, 3] = -0.2 myCopula = ot.NormalCopula(ot.NormalCopula.GetCorrelationFromSpearmanCorrelation(R)) myDistribution = ot.ComposedDistribution([E, F, L, II], myCopula) .. GENERATED FROM PYTHON SOURCE LINES 78-80 Create the design of experiments -------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 82-83 We consider a simple Monte-Carlo sampling as a design of experiments. This is why we generate an input sample using the `getSample` method of the distribution. Then we evaluate the output using the `model` function. .. GENERATED FROM PYTHON SOURCE LINES 85-89 .. code-block:: default sampleSize_train = 10 X_train = myDistribution.getSample(sampleSize_train) Y_train = model(X_train) .. GENERATED FROM PYTHON SOURCE LINES 90-92 Create the metamodel -------------------- .. GENERATED FROM PYTHON SOURCE LINES 94-95 In order to create the kriging metamodel, we first select a constant trend with the `ConstantBasisFactory` class. Then we use a squared exponential covariance model. Finally, we use the `KrigingAlgorithm` class to create the kriging metamodel, taking the training sample, the covariance model and the trend basis as input arguments. .. GENERATED FROM PYTHON SOURCE LINES 97-120 .. code-block:: default dimension = myDistribution.getDimension() basis = ot.ConstantBasisFactory(dimension).build() # Trick B, v2 x_range = X_train.getMax() - X_train.getMin() print("x_range:") print(x_range) scale_max_factor = 4.0 # Must be > 1, tune this to match your problem scale_min_factor = 0.1 # Must be < 1, tune this to match your problem maximum_scale_bounds = scale_max_factor * x_range minimum_scale_bounds = scale_min_factor * x_range scaleOptimizationBounds = ot.Interval(minimum_scale_bounds, maximum_scale_bounds) print("scaleOptimizationBounds") print(scaleOptimizationBounds) covarianceModel = ot.SquaredExponential([1.0] * dimension, [1.0]) covarianceModel.setScale(maximum_scale_bounds) # Trick A algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis) algo.setOptimizationBounds(scaleOptimizationBounds) algo.run() result = algo.getResult() krigingMetamodel = result.getMetaModel() .. rst-class:: sphx-glr-script-out .. code-block:: none x_range: [2.12636e+07,24296.8,7.35174,106.039] scaleOptimizationBounds [2.12636e+06, 8.50545e+07] [2429.68, 97187.2] [0.735174, 29.407] [10.6039, 424.154] .. GENERATED FROM PYTHON SOURCE LINES 121-124 The `run` method has optimized the hyperparameters of the metamodel. We can then print the constant trend of the metamodel, which have been estimated using the least squares method. .. GENERATED FROM PYTHON SOURCE LINES 126-128 .. code-block:: default result.getTrendCoefficients() .. rst-class:: sphx-glr-script-out .. code-block:: none [class=Point name=Unnamed dimension=1 values=[18.0668]] .. GENERATED FROM PYTHON SOURCE LINES 129-130 We can also print the hyperparameters of the covariance model, which have been estimated by maximizing the likelihood. .. GENERATED FROM PYTHON SOURCE LINES 132-135 .. code-block:: default basic_covariance_model = result.getCovarianceModel() print(basic_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[8.39251e+07,26010.9,29.407,424.154], amplitude=[11.0321]) .. GENERATED FROM PYTHON SOURCE LINES 136-138 Get the optimizer algorithm --------------------------- .. GENERATED FROM PYTHON SOURCE LINES 140-141 The `getOptimizationAlgorithm` method returns the optimization algorithm used to optimize the :math:`{\bf \theta}` parameters of the `SquaredExponential` covariance model. .. GENERATED FROM PYTHON SOURCE LINES 143-145 .. code-block:: default solver = algo.getOptimizationAlgorithm() .. GENERATED FROM PYTHON SOURCE LINES 146-147 Get the default optimizer. .. GENERATED FROM PYTHON SOURCE LINES 149-152 .. code-block:: default solverImplementation = solver.getImplementation() solverImplementation.getClassName() .. rst-class:: sphx-glr-script-out .. code-block:: none 'TNC' .. GENERATED FROM PYTHON SOURCE LINES 153-154 The `getOptimizationBounds` method returns the bounds. The dimension of these bounds correspond to the spatial dimension of the covariance model. In the metamodeling context, this correspond to the input dimension of the model. .. GENERATED FROM PYTHON SOURCE LINES 156-159 .. code-block:: default bounds = algo.getOptimizationBounds() bounds.getDimension() .. rst-class:: sphx-glr-script-out .. code-block:: none 4 .. GENERATED FROM PYTHON SOURCE LINES 160-164 .. code-block:: default lbounds = bounds.getLowerBound() print("lbounds") print(lbounds) .. rst-class:: sphx-glr-script-out .. code-block:: none lbounds [2.12636e+06,2429.68,0.735174,10.6039] .. GENERATED FROM PYTHON SOURCE LINES 165-169 .. code-block:: default ubounds = bounds.getUpperBound() print("ubounds") print(ubounds) .. rst-class:: sphx-glr-script-out .. code-block:: none ubounds [8.50545e+07,97187.2,29.407,424.154] .. GENERATED FROM PYTHON SOURCE LINES 170-171 The `getOptimizeParameters` method returns `True` if these parameters are to be optimized. .. GENERATED FROM PYTHON SOURCE LINES 173-177 .. code-block:: default isOptimize = algo.getOptimizeParameters() print(isOptimize) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 178-180 Configure the starting point of the optimization ------------------------------------------------ .. GENERATED FROM PYTHON SOURCE LINES 182-183 The starting point of the optimization is based on the parameters of the covariance model. In the following example, we configure the parameters of the covariance model to the arbitrary values `[12.,34.,56.,78.]`. .. GENERATED FROM PYTHON SOURCE LINES 185-190 .. code-block:: default covarianceModel = ot.SquaredExponential([12.0, 34.0, 56.0, 78.0], [1.0]) covarianceModel.setScale(maximum_scale_bounds) # Trick A algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis) algo.setOptimizationBounds(scaleOptimizationBounds) # Trick B .. GENERATED FROM PYTHON SOURCE LINES 191-193 .. code-block:: default algo.run() .. GENERATED FROM PYTHON SOURCE LINES 194-198 .. code-block:: default result = algo.getResult() new_covariance_model = result.getCovarianceModel() print(new_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[8.39251e+07,26010.9,29.407,424.154], amplitude=[11.0321]) .. GENERATED FROM PYTHON SOURCE LINES 199-200 In order to see the difference with the default optimization, we print the previous optimized covariance model. .. GENERATED FROM PYTHON SOURCE LINES 202-204 .. code-block:: default print(basic_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[8.39251e+07,26010.9,29.407,424.154], amplitude=[11.0321]) .. GENERATED FROM PYTHON SOURCE LINES 205-206 We observe that this does not change much the values of the parameters in this case. .. GENERATED FROM PYTHON SOURCE LINES 208-210 Disabling the optimization -------------------------- .. GENERATED FROM PYTHON SOURCE LINES 212-213 It is sometimes useful to completely disable the optimization of the parameters. In order to see the effect of this, we first initialize the parameters of the covariance model with the arbitrary values `[12.,34.,56.,78.]`. .. GENERATED FROM PYTHON SOURCE LINES 215-219 .. code-block:: default covarianceModel = ot.SquaredExponential([12.0, 34.0, 56.0, 78.0], [91.0]) algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis) algo.setOptimizationBounds(scaleOptimizationBounds) # Trick B .. GENERATED FROM PYTHON SOURCE LINES 220-221 The `setOptimizeParameters` method can be used to disable the optimization of the parameters. .. GENERATED FROM PYTHON SOURCE LINES 223-225 .. code-block:: default algo.setOptimizeParameters(False) .. GENERATED FROM PYTHON SOURCE LINES 226-227 Then we run the algorithm and get the result. .. GENERATED FROM PYTHON SOURCE LINES 229-232 .. code-block:: default algo.run() result = algo.getResult() .. GENERATED FROM PYTHON SOURCE LINES 233-235 We observe that the covariance model is unchanged: the parameters have not been optimized, as required. .. GENERATED FROM PYTHON SOURCE LINES 237-240 .. code-block:: default updated_covariance_model = result.getCovarianceModel() print(updated_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[12,34,56,78], amplitude=[91]) .. GENERATED FROM PYTHON SOURCE LINES 241-242 The trend, however, is still optimized, using linear least squares. .. GENERATED FROM PYTHON SOURCE LINES 244-246 .. code-block:: default result.getTrendCoefficients() .. rst-class:: sphx-glr-script-out .. code-block:: none [class=Point name=Unnamed dimension=1 values=[12.0499]] .. GENERATED FROM PYTHON SOURCE LINES 247-254 Reuse the parameters from a previous optimization ------------------------------------------------- In this example, we show how to reuse the optimized parameters of a previous kriging and configure a new one. Furthermore, we disable the optimization so that the parameters of the covariance model are not updated. This make the process of adding a new point very fast: it improves the quality by adding a new point in the design of experiments without paying the price of the update of the covariance model. .. GENERATED FROM PYTHON SOURCE LINES 256-257 Step 1: Run a first kriging algorithm. .. GENERATED FROM PYTHON SOURCE LINES 259-270 .. code-block:: default dimension = myDistribution.getDimension() basis = ot.ConstantBasisFactory(dimension).build() covarianceModel = ot.SquaredExponential([1.0] * dimension, [1.0]) covarianceModel.setScale(maximum_scale_bounds) # Trick A algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis) algo.setOptimizationBounds(scaleOptimizationBounds) # Trick B algo.run() result = algo.getResult() covarianceModel = result.getCovarianceModel() print(covarianceModel) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[8.39251e+07,26010.9,29.407,424.154], amplitude=[11.0321]) .. GENERATED FROM PYTHON SOURCE LINES 271-272 Step 2: Create a new point and add it to the previous training design. .. GENERATED FROM PYTHON SOURCE LINES 274-277 .. code-block:: default X_new = myDistribution.getSample(20) Y_new = model(X_new) .. GENERATED FROM PYTHON SOURCE LINES 278-281 .. code-block:: default X_train.add(X_new) X_train.getSize() .. rst-class:: sphx-glr-script-out .. code-block:: none 30 .. GENERATED FROM PYTHON SOURCE LINES 282-285 .. code-block:: default Y_train.add(Y_new) Y_train.getSize() .. rst-class:: sphx-glr-script-out .. code-block:: none 30 .. GENERATED FROM PYTHON SOURCE LINES 286-287 Step 3: Create an updated kriging, using the new point with the old covariance parameters. .. GENERATED FROM PYTHON SOURCE LINES 289-297 .. code-block:: default algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis) algo.setOptimizeParameters(False) algo.run() result = algo.getResult() notUpdatedCovarianceModel = result.getCovarianceModel() print(notUpdatedCovarianceModel) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[8.39251e+07,26010.9,29.407,424.154], amplitude=[11.0321]) .. GENERATED FROM PYTHON SOURCE LINES 298-307 .. code-block:: default def printCovarianceParameterChange(covarianceModel1, covarianceModel2): parameters1 = covarianceModel1.getFullParameter() parameters2 = covarianceModel2.getFullParameter() for i in range(parameters1.getDimension()): deltai = abs(parameters1[i] - parameters2[i]) print("Change in the parameter #%d = %s" % (i, deltai)) return .. GENERATED FROM PYTHON SOURCE LINES 308-310 .. code-block:: default printCovarianceParameterChange(covarianceModel, notUpdatedCovarianceModel) .. rst-class:: sphx-glr-script-out .. code-block:: none Change in the parameter #0 = 0.0 Change in the parameter #1 = 0.0 Change in the parameter #2 = 0.0 Change in the parameter #3 = 0.0 Change in the parameter #4 = 0.0 .. GENERATED FROM PYTHON SOURCE LINES 311-315 We see that the parameters did not change *at all*: disabling the optimization allows one to keep a constant covariance model. In a practical algorithm, we may, for example, add a block of 10 new points before updating the parameters of the covariance model. At this point, we may reuse the previous covariance model so that the optimization starts from a better point, compared to the parameters default values. This will reduce the cost of the optimization. .. GENERATED FROM PYTHON SOURCE LINES 317-319 Configure the local optimization solver --------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 321-323 The following example shows how to set the local optimization solver. We choose the SLSQP algorithm from NLOPT. .. GENERATED FROM PYTHON SOURCE LINES 325-334 .. code-block:: default problem = solver.getProblem() local_solver = ot.NLopt(problem, "LD_SLSQP") covarianceModel = ot.SquaredExponential([1.0] * dimension, [1.0]) covarianceModel.setScale(maximum_scale_bounds) # Trick A algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis) algo.setOptimizationBounds(scaleOptimizationBounds) # Trick B algo.setOptimizationAlgorithm(local_solver) algo.run() .. GENERATED FROM PYTHON SOURCE LINES 335-338 .. code-block:: default finetune_covariance_model = result.getCovarianceModel() print(finetune_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[8.39251e+07,26010.9,29.407,424.154], amplitude=[11.0321]) .. GENERATED FROM PYTHON SOURCE LINES 339-342 .. code-block:: default printCovarianceParameterChange(finetune_covariance_model, basic_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none Change in the parameter #0 = 0.0 Change in the parameter #1 = 0.0 Change in the parameter #2 = 0.0 Change in the parameter #3 = 0.0 Change in the parameter #4 = 0.0 .. GENERATED FROM PYTHON SOURCE LINES 343-345 Configure the global optimization solver ---------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 347-350 The following example checks the robustness of the optimization of the kriging algorithm with respect to the optimization of the likelihood function in the covariance model parameters estimation. We use a `MultiStart` algorithm in order to avoid to be trapped by a local minimum. Furthermore, we generate the design of experiments using a `LHSExperiments`, which guarantees that the points will fill the space. .. GENERATED FROM PYTHON SOURCE LINES 352-356 .. code-block:: default sampleSize_train = 10 X_train = myDistribution.getSample(sampleSize_train) Y_train = model(X_train) .. GENERATED FROM PYTHON SOURCE LINES 357-358 First, we create a multivariate distribution, based on independent `Uniform` marginals which have the bounds required by the covariance model. .. GENERATED FROM PYTHON SOURCE LINES 360-363 .. code-block:: default distributions = [ot.Uniform(lbounds[i], ubounds[i]) for i in range(dim)] boundedDistribution = ot.ComposedDistribution(distributions) .. GENERATED FROM PYTHON SOURCE LINES 364-365 We first generate a Latin Hypercube Sampling (LHS) design made of 25 points in the sample space. This LHS is optimized so as to fill the space. .. GENERATED FROM PYTHON SOURCE LINES 367-377 .. code-block:: default K = 25 # design size LHS = ot.LHSExperiment(boundedDistribution, K) LHS.setAlwaysShuffle(True) SA_profile = ot.GeometricProfile(10.0, 0.95, 20000) LHS_optimization_algo = ot.SimulatedAnnealingLHS(LHS, ot.SpaceFillingC2(), SA_profile) LHS_optimization_algo.generate() LHS_design = LHS_optimization_algo.getResult() starting_points = LHS_design.getOptimalDesign() starting_points.getSize() .. rst-class:: sphx-glr-script-out .. code-block:: none 25 .. GENERATED FROM PYTHON SOURCE LINES 378-379 We can check that the minimum and maximum in the sample correspond to the bounds of the design of experiment. .. GENERATED FROM PYTHON SOURCE LINES 381-383 .. code-block:: default print(lbounds, ubounds) .. rst-class:: sphx-glr-script-out .. code-block:: none [2.12636e+06,2429.68,0.735174,10.6039] [8.50545e+07,97187.2,29.407,424.154] .. GENERATED FROM PYTHON SOURCE LINES 384-386 .. code-block:: default starting_points.getMin(), starting_points.getMax() .. rst-class:: sphx-glr-script-out .. code-block:: none (class=Point name=Unnamed dimension=4 values=[3.58268e+06,4126.37,0.875832,25.501], class=Point name=Unnamed dimension=4 values=[8.21336e+07,95739.1,28.6265,414.801]) .. GENERATED FROM PYTHON SOURCE LINES 387-388 Then we create a `MultiStart` algorithm based on the LHS starting points. .. GENERATED FROM PYTHON SOURCE LINES 390-393 .. code-block:: default solver.setMaximumIterationNumber(10000) multiStartSolver = ot.MultiStart(solver, starting_points) .. GENERATED FROM PYTHON SOURCE LINES 394-395 Finally, we configure the optimization algorithm so as to use the `MultiStart` algorithm. .. GENERATED FROM PYTHON SOURCE LINES 397-402 .. code-block:: default algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis) algo.setOptimizationBounds(scaleOptimizationBounds) # Trick B algo.setOptimizationAlgorithm(multiStartSolver) algo.run() .. GENERATED FROM PYTHON SOURCE LINES 403-406 .. code-block:: default finetune_covariance_model = result.getCovarianceModel() print(finetune_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none SquaredExponential(scale=[8.39251e+07,26010.9,29.407,424.154], amplitude=[11.0321]) .. GENERATED FROM PYTHON SOURCE LINES 407-409 .. code-block:: default printCovarianceParameterChange(finetune_covariance_model, basic_covariance_model) .. rst-class:: sphx-glr-script-out .. code-block:: none Change in the parameter #0 = 0.0 Change in the parameter #1 = 0.0 Change in the parameter #2 = 0.0 Change in the parameter #3 = 0.0 Change in the parameter #4 = 0.0 .. GENERATED FROM PYTHON SOURCE LINES 410-411 We see that there are no changes in the estimated parameters. This shows that the first optimization of the parameters worked fine. .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.240 seconds) .. _sphx_glr_download_auto_meta_modeling_kriging_metamodel_plot_kriging_hyperparameters_optimization.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_kriging_hyperparameters_optimization.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_kriging_hyperparameters_optimization.ipynb `