Solution of least-square problem using Bayesian optimization

Driver:

BayesianLeastSquares

Download script:

bayesian_least_squares.py

The target of the study is to showcase the solution of a non-linear least-squares problem from the NIST statistical reference datasets. As an example, the MGH17 problem is considered which consists of fitting a vectorial model \(\mathbf{f}(\mathbf{b}) \in \mathbb{R}^{33}\) with

\[f_i(\mathbf{b}) = b_1 + b_2 \exp(-i \cdot b_4) + b_3 \exp(-i \cdot b_5),\, i = 0, \dots, 32\]

to a target vector with 33 entries. The certified best-fit values are

\[ \begin{align}\begin{aligned}b_1 &= 0.3754100521 \pm 2.0723153551 \cdot 10^{-3}&\\b_2 &= 1.9358469127 \pm 0.22031669222&\\b_3 &= -1.464687136 \pm 0.22175707739&\\b_4 &= 0.1286753464 \pm 4.4861358114\cdot 10^{-3}&\\b_5 &= 0.2212269966 \pm 8.9471996575 \cdot 10^{-3}&\end{aligned}\end{align} \]
  1import sys,os
  2import numpy as np
  3import time
  4import pandas as pd
  5import torch
  6import matplotlib.pyplot as plt
  7import corner #run "pip install corner" if not installed
  8import emcee #run "pip install emcee" if not installed
  9
 10
 11from jcmoptimizer import Client, Study, Obseravtion
 12client = Client()
 13
 14
 15# Definition of the search domain
 16design_space = [
 17    {'name': 'b1', 'type': 'continuous', 'domain': (0,10)}, 
 18    {'name': 'b2', 'type': 'continuous', 'domain': (0.1,4)},
 19    {'name': 'b3', 'type': 'continuous', 'domain': (-4,-0.1)},
 20    {'name': 'b4', 'type': 'continuous', 'domain': (0.05,1)},
 21    {'name': 'b5', 'type': 'continuous', 'domain': (0.05,1)}
 22]
 23constraints = [
 24    {'name': 'test', 'expression': 'b2 + b3 <= 1.0'}
 25]
 26
 27# Creation of the study object with study_id 'bayesian_least_squares'
 28study = client.create_study(
 29    design_space=design_space,
 30    constraints=constraints,
 31    driver="BayesianLeastSquares",
 32    study_name="Solution of least-square problem using Bayesian optimization",
 33    study_id="bayesian_least_squares"
 34)
 35#The vectorial model function of the MGH17 problem
 36def model(x: torch.Tensor) -> torch.Tensor:
 37    s = torch.arange(33)
 38    return x[0] + x[1]*torch.exp(-s*x[3]) + x[2]*torch.exp(-s*x[4])
 39
 40#Target vector of the MGH17
 41target=torch.tensor([
 42    8.44E-01, 9.08E-01, 9.32E-01, 9.36E-01, 9.25E-01,
 43    9.08E-01, 8.81E-01, 8.50E-01, 8.18E-01, 7.84E-01,
 44    7.51E-01, 7.18E-01, 6.85E-01, 6.58E-01, 6.28E-01,
 45    6.03E-01, 5.80E-01, 5.58E-01, 5.38E-01, 5.22E-01,
 46    5.06E-01, 4.90E-01, 4.78E-01, 4.67E-01, 4.57E-01,
 47    4.48E-01, 4.38E-01, 4.31E-01, 4.24E-01, 4.20E-01,
 48    4.14E-01, 4.11E-01, 4.06E-01
 49])
 50
 51study.configure(
 52    target_vector=target.tolist(),
 53    max_iter=120,
 54)
 55# Evaluation of the black-box function for specified design parameters
 56def evaluate(study: Study, b1: float, b2: float, b3: float, b4: float, b5: float) -> Observation:
 57
 58    observation = study.new_observation()
 59    #tensor of design values to reconstruct
 60    x = torch.tensor([b1, b2, b3, b4, b5])    
 61    observation.add(model(x).tolist())
 62
 63    return observation
 64
 65# Run the minimization
 66study.set_evaluator(evaluate)
 67study.run()
 68best_sample = study.driver.best_sample
 69min_chisq = study.driver.min_objective
 70uncertainties = study.driver.uncertainties
 71print(f"Reconstructed parameters with chi-squared value {min_chisq:.4e}:")
 72for param in design_space:
 73    name = param['name']
 74    print(f"  {name} = {best_sample[name]:.3f} +/- {uncertainties[name]:.3f}")
 75
 76# Before running a Markov-chain Monte-Carlo (MCMC) sampling we converge the surrogate
 77# models by sampling around the minimum. To make the study more explorative, the
 78# scaling parameter is increased and the effective degrees of freedom is set to one.
 79study.configure(
 80    scaling=10.0,
 81    effective_DOF=1.0, 
 82    min_uncertainty=min_chisq*1e-8,
 83    max_iter=150,
 84    min_val=0.0
 85)
 86study.run()
 87
 88# Run the MCMC sampling with 32 walkers
 89num_walkers, max_iter = 32, 10000
 90mcmc_result = study.driver.run_mcmc(
 91    rel_error=0.01,
 92    num_walkers=num_walkers,
 93    max_iter=max_iter
 94)
 95minimum = torch.tensor([3.7541005211E-01, 1.9358469127E+00, -1.4646871366E+00,
 96              1.2867534640E-01,2.2122699662E-01])
 97fig = corner.corner(
 98    np.array(mcmc_result['samples']),
 99    quantiles=(0.16, 0.5, 0.84),
100    levels=(1-np.exp(-1.0), 1-np.exp(-0.5)),
101    show_titles=True, scale_hist=False,
102    title_fmt=".3f",
103    labels=[d['name'] for d in design_space],
104    truths=minimum.numpy()
105)
106plt.savefig("corner_surrogate.svg", transparent=True) 
107
108# As a comparison, we run the MCMC sampling directly on the analytic model.
109p0 = 0.05*np.random.randn(num_walkers, len(design_space))
110p0 += minimum.numpy()
111min_chisq_cert = 5.4648946975E-05 #certified minimum of MGH17 problem
112#reduced standard error sqrt(chisq/DOF) to scale measurement uncertainties
113RSE = np.sqrt(min_chisq_cert/(len(target)-len(design_space)))
114
115#log probability function
116def log_prob(x):
117    out = -0.5*np.sum(((model(torch.tensor(x))-target)/RSE).numpy()**2)
118    if np.isnan(out): return -np.inf
119    return out
120
121sampler = emcee.EnsembleSampler(
122    nwalkers=num_walkers, ndim=len(design_space), log_prob_fn=log_prob
123)
124
125#burn-in phase
126state = sampler.run_mcmc(p0, 100)
127sampler.reset()
128#actual MCMC sampling 
129sampler.run_mcmc(state, max_iter, progress=True)
130samples = sampler.get_chain(flat=True)
131fig = corner.corner(
132    samples, quantiles=(0.16, 0.5, 0.84),
133    levels=(1-np.exp(-1.0), 1-np.exp(-0.5)),
134    show_titles=True, scale_hist=False,
135    title_fmt=".3f",
136    labels=[d['name'] for d in design_space],
137    truths=minimum.numpy()
138)
139plt.savefig("corner_analytic.svg", transparent=True)
140
141
142client.shutdown_server()
MCMC sampling based on surrogate

Markov-Chain Monte-Carlo (MCMC) sampling of the probability density of the parameters \(b_1,\dots,b_5\) based on the analytic model function.

MCMC sampling based on surrogate

Markov-Chain Monte-Carlo (MCMC) sampling of the probability density of the parameters \(b_1,\dots,b_5\) based on the trained surrogate of the study. A comparison between the analytic and the surrogate model function shows a good quantitative agreement.