# Basics

`LaplaceBoTorchSurrogate` is a BoTorch `Model`. Essentially, it’s a drop-in alternative to `SingleTaskGP`: swap the model, and the rest of the BoTorch loop stays the same. Let’s look at the surrogate on a 1D problem first.

``` python
import matplotlib.pyplot as plt
import torch
from botorch.acquisition import LogExpectedImprovement
from botorch.models.transforms.outcome import Standardize
from torch import nn

from laplacekit_bayesopt import LaplaceBoTorchSurrogate

torch.set_default_dtype(torch.float64)
torch.manual_seed(0)


def objective(x):
    # The Forrester function, negated, since BoTorch maximizes.
    return -((6 * x - 2) ** 2) * torch.sin(12 * x - 4)


train_X = torch.rand(6, 1)
train_Y = objective(train_X)
```

The surrogate takes a network and the data. Its constructor trains the network and fits the Laplace approximation, so there is no separate fit step.

``` python
def make_net():
    return nn.Sequential(
        nn.Linear(1, 50),
        nn.Tanh(),
        nn.Linear(50, 50),
        nn.Tanh(),
        nn.Linear(50, 1),
    )


model = LaplaceBoTorchSurrogate(
    make_net(),
    train_X,
    train_Y,
    outcome_transform=Standardize(m=1),
)
```

`model.posterior` is joint over the points of a batch. For the marginals at many points, we give each point its own batch, `X.unsqueeze(-2)`.

``` python
x = torch.linspace(0, 1, 200).unsqueeze(-1)
acq = LogExpectedImprovement(model, best_f=train_Y.max())

with torch.no_grad():
    post = model.posterior(x.unsqueeze(-2))
    mean, std = post.mean.squeeze(), post.variance.sqrt().squeeze()
    ei = acq(x.unsqueeze(-2)).exp()

t = x.squeeze()
fig, (top, bottom) = plt.subplots(
    2, 1, figsize=(7, 5), sharex=True, height_ratios=[3, 1]
)
top.plot(t, objective(t), "--", color="0.5", label="objective")
top.plot(t, mean, label="mean")
top.fill_between(
    t, mean - 2 * std, mean + 2 * std, alpha=0.3, label="mean ± 2 std"
)
top.scatter(train_X.squeeze(), train_Y.squeeze(), color="k", zorder=3)
top.legend()
bottom.plot(t, ei)
bottom.axvline(t[ei.argmax()], color="0.5", linestyle=":")
bottom.set_ylabel("EI")
plt.show()
```

![](basics_files/figure-html/cell-4-output-1.png)

The posterior is the linearized Laplace approximation (which is theoretically a Gaussian process!). So, as with a GP, the band is narrow at the data and wide between them. Expected improvement is largest where the mean is high and the band is wide.

## A loop

Now let’s minimize the 2D Branin function, starting from 5 points. As with BoTorch’s own models, we build a new surrogate from all the data in each round.

``` python
from botorch.models.transforms.input import Normalize
from botorch.optim import optimize_acqf
from botorch.test_functions import Branin
from botorch.utils.sampling import draw_sobol_samples

problem = Branin(negate=True)
bounds = problem.bounds

torch.manual_seed(3)
train_X = draw_sobol_samples(bounds=bounds, n=5, q=1, seed=3).squeeze(1)
train_Y = problem(train_X).unsqueeze(-1)


def make_net():
    return nn.Sequential(
        nn.Linear(2, 50),
        nn.Tanh(),
        nn.Linear(50, 50),
        nn.Tanh(),
        nn.Linear(50, 1),
    )


best = [-train_Y.max().item()]

for _ in range(15):
    model = LaplaceBoTorchSurrogate(
        make_net(),
        train_X,
        train_Y,
        input_transform=Normalize(d=2),
        outcome_transform=Standardize(m=1),
    )
    # Everything below stays the same!
    acq = LogExpectedImprovement(model, best_f=train_Y.max())
    x, _ = optimize_acqf(
        acq, bounds=bounds, q=1, num_restarts=10, raw_samples=64
    )
    train_X = torch.cat([train_X, x])
    train_Y = torch.cat([train_Y, problem(x).unsqueeze(-1)])
    best.append(-train_Y.max().item())

print(f"start:    best = {best[0]:.3f}")

for i, b in enumerate(best[1:]):
    print(f"round {i + 1:2d}: best = {b:.3f}")
```

    start:    best = 20.487
    round  1: best = 10.961
    round  2: best = 7.030
    round  3: best = 0.401
    round  4: best = 0.401
    round  5: best = 0.401
    round  6: best = 0.401
    round  7: best = 0.401
    round  8: best = 0.401
    round  9: best = 0.401
    round 10: best = 0.401
    round 11: best = 0.401
    round 12: best = 0.401
    round 13: best = 0.401
    round 14: best = 0.401
    round 15: best = 0.401

Branin’s minimum is 0.398. We only do 15 rounds here so that the page runs quickly. In practice, BO runs for hundreds or thousands of rounds.

Since the surrogate is a BoTorch `Model`, the rest of BoTorch works with it: batch and Monte Carlo acquisition functions, fantasies (`qKnowledgeGradient`, say), and Thompson sampling. The pages under “With BoTorch” show some of them.
