Metamodels
Linear Basis Function Models
Linear basis function models are a simple class of metamodels that express the predicted output as a linear combination of basis functions evaluated for the input variables defined as
where
Monomial Basis
Monomial basis functions are defined as the powers, or products of powers in the multivariate case, of the input variables with a total degree of less than or equal to
The construction of this MonomialBasis is presented next.
φ = MonomialBasis(2, 3)MonomialBasis(2, 3, Monomials.Monomial[1, x2, x1, x2², x1x2, x1², x2³, x1x2², x1²x2, x1³])By default the MonomialBasis includes the constant (zero degree) term. This behaviour can be changed by passing the include_zero=false keyword.
Radial Basis
A radial basis function (RBF) is a real-valued function
Gaussian
here, GaussianRadialBasis struct.
Polyharmonic
Note, that polyharmonic radial basis functions do not require a shape parameter. These RBs can be constructed using the PolyharmonicRadialBasis type.
Least Squares
Despite the nonlinearity of the basis functions, the model remains linear in its parameters, which allows efficient estimation of the weights using ordinary least squares. Given
The optimal weight vector is found by minimizing the sum-of-squares error
yielding the closed-form solution via
where
Example
Consider the function
where
We use HaltonSample through QuasiMonteCarloSampling to sample 128 data points from the input variable, evaluate the model, and fit a LinearBasisFunctionModel using a MonomialBasis of degree
using QuasiMonteCarlo
x = RandomVariable(Uniform(-5, 5), :x)
y = Model(
df -> df.x .* cos.(df.x),
:y,
)
data = UncertaintyQuantification.sample(x, QuasiMonteCarloSampling(128, QuasiMonteCarlo.HaltonSample()))
evaluate!(y, data)
lbfm = LinearBasisFunctionModel(data, :y, MonomialBasis(1, 9))ResponseSurface(MonomialBasis(1, 9, Monomials.Monomial[1, x1, x1², x1³, x1⁴, x1⁵, x1⁶, x1⁷, x1⁸, x1⁹]), [-1.4731392123329915e-15, 0.9878872285555937, 3.1092331928201013e-15, -0.48921945104270304, -8.629845945456308e-16, 0.038977769306528395, 7.162688064989151e-17, -0.001110963195616392, -1.7771255313697286e-18, 1.1592140784850822e-5], [:x], :y)A plot comparing the resulting model to the data points is presented next.
Response Surface
A linear basis function model constructed from a MonomialBasis is also known as a polynomial Response Surface [31]. For this reason we provide a convenient alias ResponseSurface. Using this alias the previous example can be adapted as follows.
rs = ResponseSurface(data, :y, 9)ResponseSurface(MonomialBasis(1, 9, Monomials.Monomial[1, x1, x1², x1³, x1⁴, x1⁵, x1⁶, x1⁷, x1⁸, x1⁹]), [-1.4731392123329915e-15, 0.9878872285555937, 3.1092331928201013e-15, -0.48921945104270304, -8.629845945456308e-16, 0.038977769306528395, 7.162688064989151e-17, -0.001110963195616392, -1.7771255313697286e-18, 1.1592140784850822e-5], [:x], :y)Design Of Experiments
Several experimental designs have been developed to efficiently estimate ResponseSurface models [31]. Although designed for response surface methodology these designs can be used to fit any metamodel. However, for more complex models we suggest using Quasi Monte Carlo sampling schemes instead.
The designs implemented in UncertaintyQuantification are TwoLevelFactorial, FullFactorial, FractionalFactorial, CentralComposite, BoxBehnken, and PlackettBurman.
Interval Predictor Model
An interval predictor model (IPM)[32] is a function that returns an interval instead of a precise value for the dependent variable given as
where
Using the defining vertices of P
with
and
Here,
The distance between the lower and upper bound given by
is known as the spread of the IPM. The optimal defining vertices for a given data set are found by minimizing the average spread such that all data points fall into the IPM by solving the following convex constrained optimization problem.
Example
Consider the function
where IntervalPredictorModel using a MonomialBasis of sixth degree.
using QuasiMonteCarlo
x = RandomVariable(Uniform(-5.5, 5.5), :x)
data = UncertaintyQuantification.sample(x, QuasiMonteCarloSampling(128, QuasiMonteCarlo.HaltonSample()))
m = Model(
df ->
df.x .^ 2 .* cos.(df.x) .- sin.(3 * df.x) .* exp.(-df.x .^ 2) .- df.x .-
cos.(df.x .^ 2) .+ df.x .* randn(size(df, 1)),
:y,
)
evaluate!(m, data)
b = MonomialBasis(1,6)
ipm = IntervalPredictorModel(data, :y, b)IntervalPredictorModel{MonomialBasis}(MonomialBasis(1, 6, Monomials.Monomial[1, x1, x1², x1³, x1⁴, x1⁵, x1⁶]), [-1.4224084846814096, -2.5336058220673143, -1.339493826478677, 0.12288735959842562, 0.014694344649409432, -0.005758753777371302, 0.0019200592878556367], [5.588634299641889, 0.09513494353640674, -1.3394938264771277, 0.12288735959845298, 0.014694344649409176, -0.005758753777371916, 0.0019200592878554714], [:x], :y, 128)The following figure presents the bounds of the resulting IPM and the corresponding least squares solution. Note, that the least squares solution is not guaranteed to be between the bounds of the IPM.
IPM reliability
The reliability of the IPM, that is the probability that and unobserved data point reliability function. The function reliability(ipm, ϵ) returns the confidence parameter
1 - reliability(ipm, 0.1548)0.9441622843407785Reliability analysis
As the IPM is an imprecise model, it can only be applied in a reliability analysis using the DoubleLoop or RandomSlicing. For more information, see Imprecise Reliability Analysis.
Gaussian Process Regression
Theoretical Background
A Gaussian Process (GP) is a collection of random variables, any finite subset of which has a joint Gaussian distribution. It is fully specified by a mean function
This prior GP specifies that any finite collection of function values follows a multivariate normal distribution.
To define a prior GP we use AbstractGPs.jl for the GP interface and mean function, and KernelFunctions.jl for the definition of a covariance kernel. Below, we construct a simple prior GP with a constant zero mean function and a scaled squared exponential kernel:
using UncertaintyQuantification
mean_f = ConstMean(0.0)
kernel = SqExponentialKernel() ∘ ScaleTransform(3.0)This GP object illustrates the underlying prior. The GaussianProcess constructors create that prior internally from the mean and kernel keywords, which default to ZeroMean() and SqExponentialKernel(). Pass these components directly when fitting a surrogate.
The composition operator
Posterior Gaussian Process
The posterior GP represents the distribution of functions after incorporating observed data. We denote the observation data as:
where
For a new input location
where:
is the covariance matrix with entries , is the covariance matrix with entries ,and
is the variance at the unknown input location.
We can then obtain the posterior distribution of
with
In the noisy observation case, the covariance between training points is adjusted by adding the noise variance:
The computation of the posterior predictive distribution generalizes straightforwardly to multiple input locations, providing both the posterior mean, which can serve as a regression estimate of the unknown function, and the posterior variances, which quantify the uncertainty at each point. Because the posterior is multivariate Gaussian, one can also sample function realizations at specified locations to visualize possible functions consistent with the observed data.
To fit a GP from observed data, supply a DataFrame and the output column name. The constructor optimizes the hyperparameters by default and fits the posterior used to predict learn_hyperparameters = false to keep the specified prior hyperparameters fixed.
The optional third positional argument selects the GP input columns, for example GaussianProcess(df, :y, [:x]; ...). By default, all columns except the output are used. With normalize = true (the default), this data-based constructor standardizes input columns using their training-data means and standard deviations. The same transformation is applied during prediction; outputs remain on their original scale. Use normalize = false to disable input normalization.
The following fits a GP with mean function ConstMean(0.0) and a scaled SqExponentialKernel(). While ConstMean(0.0) and ZeroMean() initially provide the same zero mean, ConstMean(0.0) allows the constant to be optimized. We also equip the GP with small observation noise mean and kernel, and set learn_noise = true to also optimize the observation-noise variance. Noise learning only takes effect when learn_hyperparameters = true.
x = collect(range(0, 10, 10))
y = sin.(x) + 0.3 * cos.(2 .* x)
df = DataFrame(x = x, y = y)
mean_f = ConstMean(0.0)
kernel = SqExponentialKernel() ∘ ScaleTransform(3.0)
σ² = 1e-5
gp_model = GaussianProcess(
df, :y;
mean = mean_f,
kernel = kernel,
normalize = true,
σ² = σ²,
learn_noise = true,
)Now we can use our GP model to predict at new input locations x_test using the evaluate! function. By default this will only write the predictive mean to the DataFrame in a column suffixed with _mean. Passing the variance=true keyword will also return the variance in a column suffixed with _var. The predictive variance includes the observation-noise variance gp_model.σ². Should only the variance be required, returning the mean can be disabled by passing the keyword mean=false.
x_test = collect(range(0, 5, 500))
prediction = DataFrame(:x => x_test)
evaluate!(gp_model, prediction; variance=true)
prediction_mean = prediction[!, :y_mean]
prediction_std = sqrt.(prediction[!, :y_var])
p = plot(x_test, prediction_mean, color=:blue, label="Mean prediction")
plot!(
x_test, prediction_mean, ribbon=2 .* prediction_std,
color=:grey, alpha=0.5, label="Confidence band"
)
y_true = sin.(x_test) + 0.3 * cos.(2 .* x_test)
plot!(x_test, y_true, color=:red, label="True function")Sampling the posterior GP
Use sample! to draw realizations of the fitted GP at a collection of input locations. The third positional argument is the number of samples (default 1). The resulting samples are stored as vectors for each location, preserving the posterior correlations between points. The draws include observation noise with variance gp_model.σ² and remain on the original output scale.
For the same one-dimensional example, we draw five realizations and plot them alongside the predictive mean, a band of two predictive standard deviations, and the training observations:
sample_data = DataFrame(x = collect(range(0, 10; length = 100)))
n = 5
sample!(gp_model, sample_data, n)
evaluate!(gp_model, sample_data; variance=true)
p_samples = plot(
sample_data.x, permutedims(hcat(sample_data.y...));
label = permutedims(["Sample $i" for i in 1:n]),
linewidth = 1.2, alpha = 0.8, xlabel = "x", ylabel = "y",
)
plot!(
p_samples, sample_data.x, sample_data.y_mean;
ribbon = 2 .* sqrt.(sample_data.y_var), fillalpha = 0.15,
color = :black, linewidth = 2, label = "GP mean ± 2σ",
)
scatter!(p_samples, df.x, df.y; color = :black, markersize = 4, label = "Training data")Repeated calls replace sample columns with matching names and leave other columns unchanged. Random.seed! makes the draws reproducible. Joint sampling factors a covariance matrix over the requested locations; a moderate plotting grid keeps this affordable. Nearly coincident points can cause numerical difficulties if the observation-noise variance is too small.
Hyperparameter optimization
GP models typically contain hyperparameters in their mean functions
A common approach to selecting hyperparameters is maximum likelihood estimation (MLE) (see, e.g. [33]), where we maximize the likelihood of observing the training data
The marginal likelihood of the observed training outputs
where
For numerical reasons, the logarithm of the marginal likelihood is typically used. Maximizing the log marginal likelihood with respect to the hyperparameters then yields the parameters that best explain the observed data. After obtaining the optimal hyperparameters, the posterior GP can be constructed as described above.
UncertaintyQuantification.jl provides a default optimizer for the hyperparameters based on the MaximumLikelihoodEstimation constructor.
optimizer = MaximumLikelihoodEstimation(
Optim.LBFGS(), Optim.Options(; iterations = 100, show_trace = false)
)If other options are desired, a different optimizer can be constructed based on Optim.jl. The script below shows the difference between an optimized and unoptimized GP.
using Optim
optimization = MaximumLikelihoodEstimation(
Optim.LBFGS(),
Optim.Options(; iterations = 10, show_trace = false)
)
gp_model = GaussianProcess(
df, :y;
σ² = σ²,
mean = mean_f,
kernel = kernel,
optimizer = optimization,
)
gp_model_unoptimized = GaussianProcess(
df, :y;
σ² = σ²,
mean = mean_f,
kernel = kernel,
learn_hyperparameters = false,
)
prediction = DataFrame(:x => x_test)
prediction_unopt = DataFrame(:x => x_test)
evaluate!(gp_model, prediction;variance=true)
evaluate!(gp_model_unoptimized, prediction_unopt; variance=true)Internally, MaximumLikelihoodEstimation() uses the LBFGS optimizer with up to 100 iterations per run and five additional randomized restarts by default. The restarts keyword controls the number of additional runs. Note that any other first-order optimizer supported by Optim.jl, along with its corresponding hyperparameters, can also be used when constructing MaximumLikelihoodEstimation.
During optimization, GP hyperparameters learn_noise = true.
We support the automatic extraction of hyperparameters from mean functions provided by AbstractGPs.jl, with the exception of:
- Custom mean functions
CustomMean. These are defined with a custom function that itself could depend on hyperparameters. These additional hyperparameters are ignored in the optimization.
Kernel functions are defined with the kernels and transformations provided by KernelFunctions.jl. For similar reasons as with CustomMean, we do not extract potential function hyperparameters from the following kernels or transforms:
- Transforms defined with custom functions
FunctionTransform.
Further, GP models containing the following kernels are not supported for hyperparameter optimization currently:
Multi-output kernels
MOKernel,Neural kernel networks
NeuralKernelNetwork,The
GibbsKernel, whose lengthscale is defined by a function.
Adaptive Gaussian Process Regression
Fitting a good GP surrogate can require many expensive model evaluations if the initial experimental design is chosen naively. Adaptive (or active learning) Gaussian process regression instead starts from a small initial design and iteratively enriches the training data: at each iteration a set of candidate points is sampled from the input space, an acquisition function (also called a learning function) scores every candidate, the most promising candidate is evaluated with the true (expensive) model, and the GP is refitted with the enlarged training set. AdaptiveGaussianProcess performs the specified number of adaptive iterations; it does not stop early based on an acquisition function's convergence criterion.
The AdaptiveGaussianProcess function drives this loop. It first constructs (or accepts) an initial GaussianProcess, then calls evaluate! on the supplied model for each newly selected point.
x = RandomVariable(Uniform(-10, 10), :x1)
model = Model(df -> sin.(df.x1) .* df.x1 .^ 2, :y)
mean_f = ConstMean(0.0)
kernel = Matern52Kernel()
n_design_points = 10
design = QuasiMonteCarloSampling(n_design_points, LatinHypercubeSample())
n_added_points = 5
adaptive_gp = AdaptiveGaussianProcess(
x,
model,
design,
:y,
MaximumVariance(),;
mean = mean_f,
kernel = kernel,
normalize = true,
candidate_sampling = MonteCarlo(1000),
)
refine!(adaptive_gp, n_added_points)As with GaussianProcess(x, model, design, :y; ...), the design positional argument specifies the sampling method and number of initial points. Here, it draws ten points with Latin hypercube sampling. The candidate_sampling keyword controls the candidates sampled at each adaptive iteration: this example uses MonteCarlo(1000), while the default is MonteCarlo(100_000). Hyperparameters are re-optimized after every added point unless learn_hyperparameters = false.
For constructors that sample from input distributions, normalize = true maps the inputs to standard normal space using those distributions. The transformation is retained during adaptive refits, and adaptive_gp.data stores the training data in physical space. The optional vector of input names follows n_added_points in the adaptive constructor.
You can also refine a fitted GP with AdaptiveGaussianProcess(gp_model, x, model, acquisition_function, n_added_points; ...). Refinement appends rows to the supplied training data; pass copy(data) or deepcopy(gp_model) to preserve the original. Duplicate training rows are not appended.
The resulting adaptive_gp is a regular GaussianProcess and can be evaluated as usual.
using DataFrames
using Plots
test_data = DataFrame(x1 = -10:0.1:10)
evaluate!(adaptive_gp, test_data; variance=true)
evaluate!(model, test_data)
p = plot(test_data.x1, test_data.y_mean; ribbon = 2 .* sqrt.(test_data.y_var), label = "GP mean ± 2σ", xlabel = "x₁", ylabel = "y", color = :blue, alpha = 0.5)
plot!(p, test_data.x1, test_data.y; label = "True function", color = :red, linestyle = :dash)
scatter!(p, adaptive_gp.gp.data.x1[1:n_design_points], adaptive_gp.gp.data.y[1:n_design_points]; label = "Initial design", color = :black)
scatter!(p, adaptive_gp.gp.data.x1[(n_design_points + 1):end], adaptive_gp.gp.data.y[(n_design_points + 1):end]; label = "Adaptively added")Acquisition Functions
The acquisition function determines which candidate point is added next, and therefore what the adaptive scheme optimizes for. Given the posterior mean
UncertaintyQuantification.jl provides the following acquisition functions to adapatively refine GP regression models; we separate them by there main area of application:
General active learning
Goal: improve the global fit of the GP
MaximumVariancesimply adds the point of maximum posterior variance,
MaximinDistanceis a space-filling criterion that adds the candidate farthest (in input space) from every existing training point ,
ExpectedImprovementForGlobalFit(EIGF) trades off the local discrepancy to the nearest training observation (with ) against the posterior variance,
Bayesian optimization
Goal: refine the global minimum
ExpectedImprovementwith exploration parameter ,
where
UpperConfidenceBoundwith exploration weight minimizes a lower confidence bound (for a minimization objective),
Reliability analysis
Goal: refine the limit-state surface
DeviationNumber, the -function used in AK-MCS, adds the point closest to the limit state relative to its uncertainty,
ExpectedFeasibility(EFF) integrates the probability that the true response lies within an -band around the limit state,