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