Metamodels
Design Of Experiments
Design Of Experiments (DOE) offers various designs that can be used for creating a model of a given system. The core idea is to evaluate significant points of the system in order to obtain a sufficient model while keeping the effort to achieve this relatively low. Depending on the parameters, their individual importance and interconnections, different designs may be adequate.
The ones implemented here are TwoLevelFactorial, FullFactorial, FractionalFactorial, CentralComposite and BoxBehnken.
Response Surface
A Response Surface is a structure used for modeling. It can be trained by providing it with evaluated points of a function. It will then, using polynomial regression, compute a model of that function.
Example
In this example, we will model the following test function (known as Himmelblau's function)
in the range
At first we need to create an array of random variables, that will be used when evaluating the points that our design produces. It will also define the range of the function we want the design to fit. This is also a good time to declare the function that we are working with.
using UncertaintyQuantification
x = RandomVariable.(Uniform(-5, 5), [:x1, :x2])
himmelblau = Model(
df -> (df.x1 .^ 2 .+ df.x2 .- 11) .^ 2 .+ (df.x1 .+ df.x2 .^ 2 .- 7) .^ 2, :y
)Model(Main.var"#2#3"(), :y, false)Our next step is to chose the design we want to use and if required, set the parameters to the values we need or want. In this example, we are using a FullFactorial design:
design = FullFactorial([5, 5])FullFactorial([5, 5], 0.99)After that, we call the sample function with our design. This produces a matrix containing the points of our design fitted to the range defined via the RandomVariables. Wer then evaluate the function we want to model in these points and use the resulting data to train a ResponseSurface. The ResponseSurface uses regression to fit a polynomial function to the given datapoints. That functions degree is set as an Integer in the constructor.
Note
The choice of the degree and the design and its parameters may be crucial to obtaining a sufficient model.
training_data = UncertaintyQuantification.sample(x, design)
evaluate!(himmelblau, training_data)
rs = ResponseSurface(training_data, :y, 4)
test_data = UncertaintyQuantification.sample(x, 1000)
evaluate!(rs, test_data)To evaluate the ResponseSurfaceuse evaluate!(rs::ResponseSurface, data::DataFrame) with the DataFrame containing the points you want to evaluate.
The model in this case has an mse of about 1e-26 and looks like this in comparison to the original:
Gaussian Process Regression
Himmelblau's Function
In this example, we will model the following test function (known as Himmelblau's function) in the range
It is defined as:
Analogue to the response surface example, we create an array of random variables, that will be used when evaluating the points that our experimental design produces.
using UncertaintyQuantification
using QuasiMonteCarlo
x = RandomVariable.(Uniform(-5, 5), [:x1, :x2])
himmelblau = Model(
df -> (df.x1 .^ 2 .+ df.x2 .- 11) .^ 2 .+ (df.x1 .+ df.x2 .^ 2 .- 7) .^ 2, :y
)Next, we choose an experimental design. Here, QuasiMonteCarloSampling(80, LatinHypercubeSample()) specifies both the sampling method and the number of training points:
design = QuasiMonteCarloSampling(80, LatinHypercubeSample())QuasiMonteCarloSampling(80, QuasiMonteCarlo.LatinHypercubeSample(Random.TaskLocalRNG()))Next, we choose the prior mean and kernel, which we will pass directly to the constructor. Here we use a constant mean of 0.0 and a squared exponential kernel. The constructor adds a small observation-noise variance (σ² = 1.0e-10 by default) for numerical stability:
mean_f = ConstMean(0.0)
kernel = SqExponentialKernel()Squared Exponential Kernel (metric = Distances.Euclidean(0.0))Next, we set up an optimizer used in the log marginal likelihood maximization to find the optimal hyperparameters of our GP model. Here we use the Adam optimizer from the Optim.jl package with a learning rate of 0.005 and run it for 10 iterations:
using Optim
optimizer = MaximumLikelihoodEstimation(Optim.Adam(alpha = 0.005), Optim.Options(; iterations = 10, show_trace = false))The constructor takes the input random variables, model, design, and output symbol as positional arguments. The prior is specified with the mean and kernel keywords. With normalize = true (the default), this constructor maps the inputs to standard normal space using their distributions. Predictions apply the same transformation automatically, while training data and outputs remain in physical space. Set normalize = false to use physical-space inputs directly. When constructing a GP from a DataFrame instead, normalize = true standardizes input columns using their training-data means and standard deviations.
Here, both input variables are used as GP features. An optional vector of input names after :y can select the feature columns explicitly, for example [:x1, :x2].
gp_model = GaussianProcess(
x,
himmelblau,
design,
:y;
mean = mean_f,
kernel = kernel,
normalize = true,
optimizer = optimizer
)The constructor optimizes the hyperparameters by maximizing the log marginal likelihood, then fits the posterior used for predictions. Set learn_hyperparameters = false to keep the specified prior hyperparameters fixed.
To evaluate the GaussianProcess, use evaluate!(gp::GaussianProcess, data::DataFrame) with the DataFrame containing the points you want to evaluate. We can evaluate the predictive mean, variance, or both. The predictions are written to columns named after the output, here :y_mean and :y_var. The default is to evaluate the mean prediction. We can specify the evaluation mode via the mode keyword argument. Supported options are:
:mean- predictive mean (default):var- predictive variance:mean_and_var- both mean and variance
test_data = UncertaintyQuantification.sample(x, 1000)
evaluate!(gp_model, test_data; variance = true)
evaluate!(himmelblau, test_data)
mse = mean((test_data.y .- test_data.y_mean) .^ 2)
println("MSE (GP): $mse")
R² = 1 - (sum((test_data.y .- test_data.y_mean) .^ 2)) / (sum((test_data.y .- mean(test_data.y)) .^ 2))
println("R^2 (GP): $R²")MSE (GP): 23.70917052404584
R^2 (GP): 0.9981396524619468The plots below compare the predicted surface with the original function. We use a grid inside the input domain, excluding the endpoints of the uniform distributions because they map to infinite values in standard normal space:
using Plots, DataFrames
a = range(-5, 5; length=200)
n = length(a)
df = DataFrame(x1=repeat(a; inner=n), x2=repeat(a; outer=n))
evaluate!(gp_model, df; variance=true)
evaluate!(himmelblau, df)
z(column) = reshape(df[!, column], n, n)
p = plot(
surface(a, a, z(:y); plot_title="Himmelblau's function"),
surface(a, a, z(:y_mean); plot_title="GP posterior mean"),
contourf(a, a, z(:y)),
contourf(a, a, z(:y_mean));
layout=(2, 2), legend=false, size=(800, 800),
)The MSE depends on the experimental design and fitted hyperparameters. The GP also provides predictive variance, including observation noise, as a measure of uncertainty:
Finally, we can visualize the absolute error between the mean prediction of the GP and the true Himmelblau function:
Adaptive Gaussian Process Regression
Adaptive Gaussian process regression enriches an initial surrogate model with new evaluations selected by a learning function. At every iteration, the algorithm samples candidate points, selects the most informative one according to the learning function, evaluates the expensive model there, and refits the Gaussian process.
Himmelblau's Function
As in the (non-adaptive) GP example, we consider the Himmelblau function in
First, define the probabilistic input and the expensive model to approximate.
x = RandomVariable.(Uniform(-5, 5), [:x1, :x2])
himmelblau = Model(
df -> (df.x1 .^ 2 .+ df.x2 .- 11) .^ 2 .+ (df.x1 .+ df.x2 .^ 2 .- 7) .^ 2, :y
)We start with the same initial Gaussian process surrogate as in the regular GP regression example. We pass the design positionally and specify mean, kernel, and normalize as keywords. With normalize = true, the input distributions define the transformation to standard normal space. To show how the GP regression improves with the adaptive, we reduced the number of QuasiMonteCarlo samples to 40, i.e., the GP model will be worse than in the regular GP example.
design = QuasiMonteCarloSampling(40, LatinHypercubeSample())
mean_f = ConstMean(0.0)
kernel = SqExponentialKernel()
optimizer = MaximumLikelihoodEstimation(Optim.Adam(alpha = 0.005), Optim.Options(; iterations = 10, show_trace = false))
initial_gp = GaussianProcess(
x,
himmelblau,
design,
:y;
mean = mean_f,
kernel = kernel,
normalize = true,
optimizer = optimizer
)Next, we update the initial GP using a selected learning function and a set number of additional points used to refine the initial GP. We use the MaximinDistance acquisition function and select 40 additional points, drawing 1000 candidates at each iteration.
learning_function = MaximinDistance()
candidate_sampling = MonteCarlo(1000)We pass the fitted GP, inputs, model, acquisition function, and number of adaptive iterations to AdaptiveGaussianProcess. The returned model is a regular GaussianProcess and retains the initial input transformation. We use deepcopy(initial_gp) because refinement appends rows to the GP's training data, and we want to preserve the initial model for comparison.
adaptive_gp = AdaptiveGaussianProcess(
deepcopy(initial_gp),
x,
himmelblau,
learning_function,
candidate_sampling;
optimizer = optimizer
)
refine!(adaptive_gp, 40)To assess the fitted surrogate, we compute the MSE between GP mean and the reference model. We compare the MSE of the initial GP and the refined GP.
We start with the initial GP:
test_data = UncertaintyQuantification.sample(x, QuasiMonteCarloSampling(1000, LatinHypercubeSample()))
test_data_adaptive = deepcopy(test_data)
evaluate!(initial_gp, test_data)
evaluate!(himmelblau, test_data)
mse = mean((test_data.y .- test_data.y_mean) .^ 2)
println("MSE (initial GP): $mse")
R² = 1 - (sum((test_data.y .- test_data.y_mean) .^ 2)) / (sum((test_data.y .- mean(test_data.y)) .^ 2))
println("R^2 (initial GP): $R²")MSE (initial GP): 411.69682433027947
R^2 (initial GP): 0.9660854046006164Then, we also evaluate the adaptively refined GP at the same test set:
evaluate!(adaptive_gp, test_data_adaptive)
evaluate!(himmelblau, test_data_adaptive)
mse_adap = mean((test_data_adaptive.y .- test_data_adaptive.y_mean) .^ 2)
println("MSE (adaptive GP): $mse_adap")
R²_adap = 1 - (sum((test_data_adaptive.y .- test_data_adaptive.y_mean) .^ 2)) / (sum((test_data_adaptive.y .- mean(test_data_adaptive.y)) .^ 2))
println("R^2 (adaptive GP): $R²_adap")MSE (adaptive GP): 0.38293754616766157
R^2 (adaptive GP): 0.9999684545248494We can clearly see from the results how both the mean squared error and the coefficient of determination have improved after the adaptive refinement.
This page was generated using Literate.jl.