BayesLeastSquare¶
Purpose¶
The goal of the driver is to mininize the reduced standard error as a function of the vector of model parameters . The reduced standard error with respect to an observed target vector (e.g. a measurement) is defined as
where is the covariance matrix of the target vector entries and it the model vector, which depends on the parameter values . The number of degrees of freedom DOF is the difference between the length of the target vector and the length of the parameter vector . If the number of degrees of freedom is negative, we set DOF=1. The reduced standard error is often also denoted as noise level or standard deviation STD. The square of the RSE is the the mean squared error MSE.
It is possible to retrieve the covariances between the model parameters at the found minimum of the RSE (see Driverspecific Information). The paramter covariance matrix gives an estimate of the uncertainties of the reconstructed parameters under the assumption that the model vector entries depend linearly on . The standard deviations of the parameter value are given as .
The driver performs a Gaussian process regression (GPR) on all entries of the model vector . From the regression model it determines parameter values which lead to a large expected improvement of the reduced standard error RSE. It converges typically faster than the standard leastsquare minimization, which is based on a LevenbergMarquardt approach.
The GPR model contains higher order dependencies on around the minimium of the RSE.
In order to determine the parameter uncertainties including nonlinear terms, it is possible to sample the probability distribution of the reconstructed parameters using a Markov chain Monte Carlo sampling (run_mcmc()
). For this sampling, it is also possible to define more complex error models (see error_model). After a MCMC sampling, the reconstructed parameter values are determined by the median value of the probability distribution. The lower uncertainty is given by the 16% quantile of the distribution and the upper uncertainty as the 84% quantile.
Usage Example¶
import sys,os
import numpy as np
import time
sys.path.append(os.path.join(os.getenv('JCMROOT'), 'ThirdPartySupport', 'Python'))
import jcmwave
client = jcmwave.optimizer.client()
# Definition of the search domain
domain = [
{'name': 'm', 'type': 'continuous', 'domain': (5,5)},
{'name': 'b', 'type': 'continuous', 'domain': (0,10)},
]
# Creation of the study object with study_id 'BayesLeastSquare_example'
study = client.create_study(domain=domain,
driver="BayesLeastSquare",
name="BayesLeastSquare example",
study_id='BayesLeastSquare_example')
# Generate some randomized data for a linear fit
np.random.seed(111)
N = 50 #number of datapoints
X = np.sort(10 * np.random.rand(N)) # random xvalues
m0, b0, f0 = 0.5, 5, 0.5 #slope, offset, Yproportional error
Y = m0 * X + b0 #data points
#add error proportional to Y
Y += f0 * np.abs(Y) * np.random.randn(N)
#add error independent of Y with mean 0.1 and and std deviation 0.5
Yerr = 0.1 + 0.5 * np.random.rand(N)
Y += Yerr * np.random.randn(N)
# Definition of the objective function including derivatives
def objective(m,b):
time.sleep(2.0) # makes objective expensive
observation = study.new_observation()
observation.add(m * X + b)
observation.add(derivative='m', value=X)
observation.add(derivative='b', value=np.ones_like(X))
return observation
# Set study parameters
study.set_parameters(target_vector=Y.tolist(), uncertainty_vector = Yerr.tolist())
# Run the minimization
study.set_objective(objective)
study.run()
# Least square error estimate
info = study.info()
driver_info = study.driver_info()
cov = driver_info['parameter_covariance']
MSE = driver_info['MSE']#mean squared error of residuum at minimum
err = np.sqrt(MSE*np.diag(cov))#error estimate
print('Error estimates of least square minimization')
for idx,p in enumerate(info['min_params']):
print("{} = {:.3f} +/ {:.3f}".format(p,info['min_params'][p],err[idx]))
# The least square estimates are based on the uncertainty vector
# and the linear approximation of the model vector y(p).
# A Markov chain Monte Carlo (MCMC) sampling allows to determine
# the probability distribution of the model parameters including nonlinear
# terms and a more realistic error model (see parameters section for details).
study.set_parameters(
error_model='sqrt(err_cov^2 + y_model^2 * exp(2*log_f))',
error_model_parameter_distribution=[
{'name':'log_f','distribution':'uniform','domain':[10,1]}
]
)
# The MCMC sampling with a more realistic error model gives more
# accurately reconstructed parameters.
mcmc_result = study.run_mcmc()
import corner
import matplotlib.pyplot as plt
fig = corner.corner(mcmc_result['samples'], quantiles=(0.16, 0.5, 0.84),
levels=(1np.exp(0.5),), show_titles=True, scale_hist=True,
labels=[d['name'] for d in domain]+['log_f'],
truths=[m0,b0,np.log(f0)])
plt.show()
Parameters¶
The following parameters can be set by calling, e.g.
study.set_parameters(example_parameter1 = [1,2,3], example_parameter2 = True)
max_iter (int):  Maximum number of evaluations of the objective function (default: inf) 

max_time (int):  Maximum run time in seconds (default: inf) 

num_parallel (int):  

Number of parallel observations of the objective function (default: 1) 
distribution (list):  

Definition of random distribution for each parameter in the format of a list. All continuous parameters with unspecified distribution are assumed to be uniformely distributed in the parameter domain. Fixed and discrete parameters are not random parameters. The value of discrete parameters defaults to the first listed value. (default: None)

optimization_step_min (int):  

Minimum number of observations of the objective before the hyperparameters are optimized (default: 2 times number of dimensions). Note: Each derivative observation is counting as an independent observation (default: None) 
optimization_step_max (int):  

Maximum number of observations of the objective after which no more hyperparameter optimization is performed. Note: Each derivative observation is counting as an independent observation (default: 300) 
optimization_interval (int):  

Maximum number of observations of the objective after which the hyperparameters are optimized. Note: Each derivative observation is counting as an independent observation (default: 20) 
compute_suggestion_in_advance (bool):  

If True a suggestion is computed in advance to speed up the sample computation. (default: True) 
num_training_samples (int):  

Number of random initial samples before the samples are drawn according to the acquisition function. (default: 0) 
parameter_uncertainties (list):  

Sometimes, one is interested in minima of the objective function that are preferably insensitive to variations of certain parameters (e.g. if the parameters have large fabrication variances). In this case, one can specify the uncertainties of those parameters, i.e. their standard deviations. The regression model of the objective is averaged over the uncertainty intervals such that very narrow local minima are averaged out whereas broad minima are not effected. Note that the averaging results in additional numerical effort that grows exponentially with the number of uncertain parameters. (default: None)

optimization_level (float):  

Steers how often the hyperparameters are optimized. Small values (e.g. 0.01) lead to more frequent optimizations. Large values (e.g. 1.0) to less frequent optimizations (default: 0.05) 
num_samples_hyperparameters (int):  

Number of local searches for optimal hyperparameters. If None, then the number is chosen accordingly to the number of dimensions. (default: None) 
num_fantasies (int):  

Number of “fantasy” samples drawn from the Gaussian process in order to average over uncertain function values. This is used for avoiding the position of running samples or to handle noisy inputs. (default: 16) 
length_scales (list):  

List of length scales for each parameter on which the objective functions varies. If not set, the length scales are chosen automatically. (default: None) 
detect_noise (bool):  

If true, variance due to noise is modelled by two hyperparameter (noise of objective and noise of derivatives). The value of the hyperparameters are chosen to maximize the likelihood of the observations. (default: False) 
noise_variance (list):  

List of noise variances for objective observations and derivative observations relative to total variance. If not set, noiseless observations are assumed. Note: If detect_noise is true, the noise variances will be optimized after optimization_step_min observations. (default: None) 
warp_input (bool):  

If true, the input function values are transformed (warped) in order to maximize the likelihood of the observations. (default: False) 
warping_strengths (list):  

List of lower and upper warping strength. If not set, function values are left unwarped. Note: If warp_input is true, the warping strengths will be optimized after optimization_step_min observations. (default: None) 
localize (bool):  

If true, a local search is performed, i.e. samples are not drawn in regions with large uncertainty. (default: False) 
horizon (int):  Horizon of previous observations to take into account for driver. (default: all previous observations are taken into account). (default: None) 

eps (float):  Stopping criterium. Minimum distance in the parameter space to the currently known minimum (default: 0.0) 

min_val (float):  

Stopping criterium. Minimum value of the objective function (default: inf) 
strategy (str):  Sampling strategy of the Bayesian optimization. (default: EI) (options: [‘EI’, ‘LCB’, ‘PoI’]) 

scaling (float):  

Scaling parameter of the model uncertainty. Default is scaling = 1.0 For scaling >> 1.0 (e.g. scaling=10) the search is more explorative. For scaling << 1.0 (e.g. scaling=0.1) the search becomes more greedy, i.e. any local minimum is intensively exploited (default: 1.0) 
vary_scaling (bool):  

If True the scaling parameter is randomly varied between 0.1 and 10 (default: True) 
post_converge (bool):  

Converge the minimization using probability of improvement after the min_PoI critereon has been met. (default: False) 
min_PoI (float):  

Stopping criterium. Minimum probability of improvement for the last 5 aqcuisitions (default: 2e12) 
min_EI (float):  Stopping criterium. Minimum expected improvement for the last 5 aqcuisitions (default: 0.0) 

target_vector (list):  

Vector of observations . (default: None) 
covariance_matrix (matrix):  

Covariance matrix . For a simple leastsquare minimization, is the identity matrix. For measurements with different uncertainties , . If not specified, is the identity matrix. (default: None) 
uncertainty_vector (list):  

Defines the vector of measurement uncertainties of the target vector . Accordingly, the covariance matrix is set to . (default: None) 
error_model (string):  

String defining error of measurement as a function of the model values

error_model_parameter_distribution (list):  

Definition of random distribution for each parameter of the error model in the format of a list. For an example, see the documentation of error_model . (default: []) 
post_converge_lm (bool):  

Converge the minimization using LevenbergMarquardt minimization after the min_PoI critereon has been met. (default: True) 
explore_max_likelihood (bool):  

If true, samples are drawn close to the maximum posterior likelihood where the uncertainty of the Gaussian process prediction is relatively large. Activating this option is useful prior to running a Makov chain Monte Carlo sampling of the posterior. (default: False)

min_UC (float):  Stopping criterium used during “explore_max_likelihood”. Minimum average uncertainty of all Gaussian processes (in units of their global stamdard deviation) for the last 5 aqcuisitions (default: 0.001) 

ftol (float):  Tolerance for termination by the change of the cost function while converging the results using GaussNewton minization. The optimization process is stopped when dF < ftol * F. (default: 1e08) 

max_scaling (float):  

Maximum scaling parameter. The scaling parameter is used to enforce a global search after convergence to a local minimum.It is automatically increased when a local convergence has been detected. (default: 100) 
max_data_hyper_optimization (int):  

Maximum number of data points (objective and derivative observations for each input) for which a hyper parameter optimization is performed. The limit is only checked if the hyperparameters were at least optimized once. In None, the value is set to max(100*len(target_vector)*len(params),self.optimization_step_max) . (default: None) 
degrees_of_freedom (float):  

Number of degrees of freedeom (DOF) used for stochastic variable of the chisquared distributio. This number indicates how many output channels of the forward model are statistically independent. Default: Automatically determined effective DOF. (default: None) 
Driverspecific Information¶
A dictionary with following parameters can be retrieved by calling
study.driver_info()
.
parameter_covariance:  

Covariance matrix of the parameters at the sampling point with minimal discrepancy. The uncertainty of the parameter is given as . 
MSE:  The mean squared error MSE is the square of the reduced standarderror (RSE). It is given as the residual sum of squares divided by the degrees of freedom (DOF), i.e. the length of the target vector M minus the number of parameters N: MSE=RSS/(MN). 
