# Thompson sampling

Thompson sampling draws one function from the posterior and evaluates the point where that function is largest. Importing `laplacekit_bayesopt` registers the surrogate with BoTorch’s `draw_matheron_paths`, so BoTorch’s `PathwiseThompsonSampling` works with it. The functions are drawn from the linearized Laplace posterior over the weights.

We minimize Branin over a fixed set of Sobol points, as in BoTorch’s Thompson sampling tutorials.

``` python
import torch
from botorch.acquisition.thompson_sampling import PathwiseThompsonSampling
from botorch.models.transforms.input import Normalize
from botorch.models.transforms.outcome import Standardize
from botorch.optim import optimize_acqf_discrete
from botorch.test_functions import Branin
from botorch.utils.sampling import draw_sobol_samples
from torch import nn

from laplacekit_bayesopt import LaplaceBoTorchSurrogate

torch.set_default_dtype(torch.float64)
torch.manual_seed(5)

problem = Branin(negate=True)
bounds = problem.bounds
candidates = draw_sobol_samples(bounds=bounds, n=2**13, q=1, seed=0)
candidates = candidates.squeeze(1)

train_X = candidates[:20]
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 = []

for _ in range(15):
    model = LaplaceBoTorchSurrogate(
        make_net(),
        train_X,
        train_Y,
        input_transform=Normalize(d=2),
        outcome_transform=Standardize(m=1),
    )
    acq = PathwiseThompsonSampling(model)
    x, _ = optimize_acqf_discrete(
        acq, q=1, choices=candidates, max_batch_size=2048
    )
    train_X = torch.cat([train_X, x])
    train_Y = torch.cat([train_Y, problem(x).unsqueeze(-1)])
    best.append(-train_Y.max().item())

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

    round  1: best = 3.545
    round  2: best = 3.545
    round  3: best = 3.545
    round  4: best = 3.545
    round  5: best = 3.545
    round  6: best = 3.545
    round  7: best = 3.545
    round  8: best = 3.545
    round  9: best = 3.545
    round 10: best = 3.545
    round 11: best = 3.545
    round 12: best = 3.545
    round 13: best = 0.735
    round 14: best = 0.735
    round 15: best = 0.735

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.

Each path is a deterministic function of its input. So, `optimize_acqf` also works with it, over the whole box instead of a fixed set.
