Homework 8#
Bayesian Optimization for Model Calibration
Coverage: Lecture 23 and the model-calibration application.
Due: Sunday, November 15, 2026, at 11:59 p.m. Eastern Time.
Total: 100 points.
Instructions#
Answer the six lettered parts. Show the requested mathematical steps in Problem 1. Short paragraphs or bullet points are sufficient in Problem 2; no separate report is required.
All computational code is supplied. Run its cells in order without editing them, and enter responses in the answer text cells. You are not expected to study the implementation or write code.
Submit a PDF of your completed notebook, including your name, answers, generated tables, and figures, through Gradescope. Check that equations and figures are legible in the PDF.
This self-contained notebook uses NumPy, SciPy, pandas, Matplotlib, and scikit-learn. The observations are generated in the notebook; no data download is required. Use a standard CPU Google Colab runtime. No package installation, Google Drive, or absolute file paths are needed.
Report approximately four significant digits. Small numerical differences between software versions are acceptable; base your interpretations on your own generated results.
Relevant course material: Bayesian global optimization and the assigned model-calibration application.
Student details#
First name:
Last name:
Purdue email:
Problem 1: Calibration loss and expected improvement (20 points)#
Credit: Course exercise using the Gaussian likelihood and the expected-improvement acquisition rule from Lecture 23. We use minimization throughout.
(a) From observations to an objective (10 points)#
Suppose \(n\) measurements satisfy \(y_i=f_i(\mathbf{k})+\epsilon_i\), where the measurement errors are independent \(N(0,\sigma^2)\) and \(\sigma\) is known. Define
Write the likelihood and show that minimizing \(J\) gives a maximum-likelihood estimate of \(\mathbf{k}\). Is this necessarily a maximum-a-posteriori estimate under a nonuniform prior? Once the observed \(y_i\) are fixed, is \(J(\mathbf{k})\) random each time a deterministic simulator evaluates it? Explain.
Your answer:
(b) An acquisition decision (10 points)#
For a loss \(g\) to be minimized, the smallest observed value is \(g_{\min}=1\). The GP’s latent predictive distribution at a candidate is \(G\sim N(\mu,s^2)\). Its expected improvement is
where \(\Phi\) and \(\phi\) are the standard normal CDF and density. The formula is supplied; do not derive it.
Candidate |
\(\mu\) |
\(s\) |
|---|---|---|
A |
0.90 |
0.05 |
B |
1.10 |
0.40 |
Use \(\Phi(2)=0.97725\), \(\phi(2)=0.053991\), \(\Phi(-0.25)=0.401294\), and \(\phi(-0.25)=0.386668\). Calculate both EIs and select the next candidate. Explain how uncertainty can favor a candidate with a worse mean prediction. Also give the EI limit as \(s\to0\).
Your answer:
Problem 2: A reaction-calibration study with a fixed simulation budget (80 points)#
Credit: This synthetic teaching study was constructed for ME 539. It uses a simplified consecutive first-order reaction to illustrate the calibration workflow; the measurements are simulated, not laboratory data or the measurements in the in-class catalysis case.
Consider \(A\rightarrow B\rightarrow C\) in a well-mixed batch reactor:
Time is in minutes, the rates are in \(\mathrm{min}^{-1}\), and concentrations are normalized by the initial concentration of A. We observe A and B at ten times, with independent Gaussian errors of standard deviation \(\sigma=0.025\). The data-generating rates are \((0.7,0.35)\,\mathrm{min}^{-1}\); they provide a teaching reference and are not used to choose search evaluations. Both rates are restricted to \([0.1,1.5]\,\mathrm{min}^{-1}\).
The supplied differential-equation solver predicts A and B. The objective \(J\) is the mean squared standardized residual over the 20 scalar observations. One objective evaluation means running that solver for one rate pair at all observation times. This small solver is fast; we impose a budget to model the decision faced when simulations are expensive.
from IPython import get_ipython
if get_ipython() is not None:
get_ipython().run_line_magic("matplotlib", "inline")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
from scipy.integrate import solve_ivp
from scipy.stats import norm
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
plt.rcParams.update({'font.size': 11, 'figure.dpi': 110})
SEED = 53908
times = np.linspace(0.5, 5.0, 10)
sigma = 0.025
def reaction(k, t):
k1, k2 = k
def rhs(time, c):
a, b, c_product = c
return [-k1*a, k1*a-k2*b, k2*b]
result = solve_ivp(rhs, [0, float(np.max(t))], [1., 0., 0.],
t_eval=t, rtol=1e-8, atol=1e-10)
if not result.success:
raise RuntimeError(result.message)
return result.y.T
# Synthetic observations: the same measurements are used in every search.
true_rates = np.array([0.7, 0.35])
observations = reaction(true_rates, times)[:, :2]
observations += np.random.default_rng(SEED).normal(0, sigma, observations.shape)
data_table = pd.DataFrame({'Time (min)': times, 'A observed': observations[:, 0],
'B observed': observations[:, 1]})
display(data_table.round(4))
fig, ax = plt.subplots(figsize=(7, 3.6))
for j, name in enumerate(['A', 'B']):
ax.errorbar(times, observations[:, j], yerr=2*sigma, fmt='o',
capsize=3, label=f'{name}: observation ± 2σ')
ax.set(xlabel='Time (min)', ylabel='Concentration / initial A concentration',
title='Fixed synthetic reaction measurements')
ax.legend(fontsize=9); ax.grid(alpha=.2); fig.tight_layout(); plt.show()
(a) Identify the calibration problem (15 points)#
Identify the unknown parameters, measured quantities, supplied physical assumptions, and the quantity being minimized. Explain why the 20 observations remain fixed while Bayesian optimization collects new information. What kind of information does one new objective evaluation add, and what would require a new physical experiment?
Your answer:
The search uses a fixed \(31\times31\) candidate grid, uniformly spaced in the logarithms of the rates. Each plotted coordinate is
The GP models \(g(\mathbf{x})=\log[1+J(\mathbf{k}(\mathbf{x}))]\). This monotone transformation preserves the minimizer but changes the acquisition decisions; EI is computed in g units. The GP uses a fixed Matérn-\(5/2\) kernel with length scale 0.28 in these coordinates. Its training outputs are centered and scaled using only the evaluated losses, then predictions are returned in g units. A small numerical diagonal term is added for stability; no measurement-noise term is added to this deterministic loss surrogate.
Six randomly selected initial evaluations fit the first GP. In the plots, white circles are evaluated candidates and the red star is the next candidate chosen by EI. Evaluating GP predictions on the grid does not call the reaction solver.
axis = np.linspace(0, 1, 31)
mesh = np.meshgrid(axis, axis, indexing='ij')
candidates = np.column_stack([a.ravel() for a in mesh])
LOW, HIGH = 0.1, 1.5
def rates_from_unit(x):
return np.exp(np.log(LOW) + np.asarray(x)*np.log(HIGH/LOW))
def objective(x):
residual = (reaction(rates_from_unit(x), times)[:, :2] - observations)/sigma
return float(np.mean(residual**2))
def fit_surrogate(indices, losses):
# The kernel is fixed; the output is centered/scaled using observed losses only.
model = GaussianProcessRegressor(kernel=Matern(length_scale=.28, nu=2.5),
alpha=1e-8, normalize_y=True, optimizer=None)
return model.fit(candidates[indices], np.log1p(losses))
def expected_improvement(mu, sd, best):
delta = best-mu
z = np.divide(delta, sd, out=np.zeros_like(delta), where=sd>1e-12)
return np.where(sd>1e-12, delta*norm.cdf(z)+sd*norm.pdf(z),
np.maximum(delta, 0))
N_INITIAL, BUDGET = 6, 24
initial = np.random.default_rng(SEED).choice(len(candidates), N_INITIAL, replace=False)
initial_losses = np.array([objective(candidates[i]) for i in initial])
gp = fit_surrogate(initial, initial_losses)
mu, sd = gp.predict(candidates, return_std=True)
ei = expected_improvement(mu, sd, np.log1p(initial_losses.min()))
ei[initial] = -np.inf
next_index = int(np.argmax(ei))
snapshot = pd.DataFrame([{'k1 (1/min)': rates_from_unit(candidates[next_index])[0],
'k2 (1/min)': rates_from_unit(candidates[next_index])[1],
'GP mean of g': mu[next_index], 'GP SD of g': sd[next_index],
'Expected improvement': ei[next_index]}])
display(snapshot.round(4))
fig, axes = plt.subplots(1, 3, figsize=(11, 3.4))
for ax, values, title in zip(axes, [mu, sd, np.maximum(ei, 0)],
['GP mean of g', 'GP standard deviation of g', 'Expected improvement']):
artist = ax.pcolormesh(axis, axis, values.reshape(31, 31).T, shading='auto')
ax.scatter(*candidates[initial].T, c='white', edgecolors='black', s=32)
ax.scatter(*candidates[next_index], c='red', marker='*', s=120)
ax.set(xlabel='Scaled log k₁', ylabel='Scaled log k₂', title=title)
fig.colorbar(artist, ax=ax, shrink=.8)
fig.tight_layout(); plt.show()
(b) Read the first acquisition decision (20 points)#
Report the selected rate pair, predicted g mean, predicted g standard deviation, and EI. Use the three panels to explain the choice. Why need the selected point minimize neither the GP mean nor the uncertainty? Explain why the GP standard deviation in this figure is not a posterior standard deviation for either reaction rate.
Your answer:
Each search now receives 24 total objective evaluations, including the six initial ones. The EI and random-search methods share the same initial six candidates within each seed. Neither method revisits an evaluated candidate. Five seed pairs use the same measurements and candidate grid, so they test sensitivity to search initialization and choices, not repeated measurement experiments. Shading shows the minimum-to-maximum range of the five best-so-far curves; it is not a credible interval or confidence interval.
def run_search(seed, method):
random = np.random.default_rng(seed)
chosen = list(random.choice(len(candidates), N_INITIAL, replace=False))
losses = [objective(candidates[i]) for i in chosen]
for step in range(N_INITIAL, BUDGET):
available = np.setdiff1d(np.arange(len(candidates)), chosen)
if method == 'EI':
model = fit_surrogate(chosen, losses)
mean, std = model.predict(candidates[available], return_std=True)
scores = expected_improvement(mean, std, np.log1p(min(losses)))
index = int(available[np.argmax(scores)])
else:
index = int(random.choice(available))
chosen.append(index)
losses.append(objective(candidates[index]))
return {'indices': np.array(chosen), 'losses': np.array(losses),
'best': np.minimum.accumulate(losses)}
runs = {(seed, method): run_search(seed, method)
for seed in range(SEED, SEED+5) for method in ['EI', 'Random']}
comparison = pd.DataFrame([{'Seed': seed,
'EI final J': runs[seed, 'EI']['best'][-1],
'Random final J': runs[seed, 'Random']['best'][-1]}
for seed in range(SEED, SEED+5)])
display(comparison.round(4))
print('Median final J:', comparison[['EI final J', 'Random final J']].median().round(4).to_dict())
fig, ax = plt.subplots(figsize=(7, 3.7))
for method, color in [('EI', 'tab:blue'), ('Random', 'tab:orange')]:
histories = np.array([runs[s, method]['best'] for s in range(SEED, SEED+5)])
ax.plot(np.arange(1, BUDGET+1), np.median(histories, axis=0), color=color, label=method)
ax.fill_between(np.arange(1, BUDGET+1), histories.min(0), histories.max(0),
alpha=.15, color=color)
ax.axvline(N_INITIAL, c='gray', ls=':', label='End of shared initialization')
ax.set(xlabel='Number of objective evaluations', ylabel='Best observed J',
yscale='log', title='Median and range across five paired searches')
ax.legend(fontsize=9); ax.grid(alpha=.2); fig.tight_layout(); plt.show()
(c) Compare the searches fairly (25 points)#
Report the median final J for each method and how many of the five pairs favor EI. How many new evaluations follow initialization in each search? Explain why counting the six initial evaluations and using the same initial points makes the comparison fairer. State one supported conclusion and two limitations of this comparison. Does a flat best-so-far curve prove that the global minimum has been found?
Your answer:
For the final check, use the first seed’s EI run, chosen in advance. The smallest evaluated loss selects one rate pair. The following curve and residual plots are post-search diagnostics; they do not supply any additional search candidates. Standardized residuals are \((y-f)/\sigma\). Their RMS equals \(\sqrt{J}\) at this pair.
selected_run = runs[SEED, 'EI']
winner = int(np.argmin(selected_run['losses']))
best_rates = rates_from_unit(candidates[selected_run['indices'][winner]])
fitted_at_data = reaction(best_rates, times)
standardized_residuals = (observations-fitted_at_data[:, :2])/sigma
display(pd.DataFrame({'Rate': ['k1', 'k2'], 'Generating value (1/min)': true_rates,
'Selected value (1/min)': best_rates}).round(4))
print(f"Selected J = {selected_run['losses'][winner]:.4f}")
print(f'Mean standardized residual = {standardized_residuals.mean():.4f}')
print(f'RMS standardized residual = {np.sqrt(np.mean(standardized_residuals**2)):.4f}')
fine_time = np.linspace(0, 5, 101)
fitted_curves = reaction(best_rates, fine_time)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.7))
for j, name in enumerate(['A', 'B']):
axes[0].plot(fine_time, fitted_curves[:, j], label=f'{name}: selected model')
axes[0].scatter(times, observations[:, j], s=24)
axes[1].plot(times, standardized_residuals[:, j], 'o-', label=name)
axes[0].set(xlabel='Time (min)', ylabel='Normalized concentration', title='Selected point calibration')
axes[1].set(xlabel='Time (min)', ylabel='(Observation − prediction) / σ', title='Residual check')
axes[1].axhline(0, c='gray', lw=1)
for ax in axes: ax.legend(fontsize=9); ax.grid(alpha=.2)
fig.tight_layout(); plt.show()
audit = {'comparison': comparison.to_dict('records'), 'best_rates': best_rates.tolist(),
'best_J': float(selected_run['losses'][winner]), 'next': snapshot.to_dict('records')}
(d) State what was calibrated (20 points)#
Report the selected rates, J, and RMS standardized residual. Compare the rates with the generating values and use the residual plot to describe the fit. Does a low loss identify the rates without uncertainty? Explain what additional inference would be needed for a credible interval on \(k_1\), and give one reason that successful recovery on these synthetic data might not transfer to a real reaction.
Your answer: