Skip to main content

Candidate sets

Sometimes, the inputs are a fixed set of candidates rather than a box to search, and they might not even be vectors: strings, say. BoTorch needs tensors, so here, LaplaceDiscreteSurrogate and the acquisition functions in laplacekit_bayesopt.discrete_acqf take over.

As a toy example, the candidates are the 4096 DNA strings of length six, and the objective is a made-up score for each string.

import itertools

import torch
from torch import nn

from laplacekit_bayesopt import LaplaceDiscreteSurrogate
from laplacekit_bayesopt.discrete_acqf import (
    expected_improvement,
    thompson_batch,
)

torch.manual_seed(0)

candidates = ["".join(s) for s in itertools.product("ACGT", repeat=6)]
weights = torch.randn(6, 4)


def objective(s):
    letters = ["ACGT".index(c) for c in s]
    position = sum(weights[i, c] for i, c in enumerate(letters))
    repeats = sum(a == b for a, b in itertools.pairwise(s))

    return float(position) + 0.5 * repeats


y = torch.tensor([objective(s) for s in candidates])
print(f"{len(candidates)} candidates, best score {y.max():.3f}")
4096 candidates, best score 5.539

The network says how it turns the strings into tensors with a prepare method. LaplaceDiscreteSurrogate passes the raw inputs through it, both when training and when predicting.

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(24, 50),
            nn.Tanh(),
            nn.Linear(50, 50),
            nn.Tanh(),
            nn.Linear(50, 1),
        )

    def prepare(self, strings):
        # One-hot, 6 positions times 4 letters.
        idx = torch.tensor([["ACGT".index(c) for c in s] for s in strings])
        return nn.functional.one_hot(idx, 4).flatten(1).float()

    def forward(self, x):
        return self.mlp(x)

Now the loop. Each round fits a new surrogate on what we have seen, predicts every candidate we haven’t, and evaluates the one with the highest expected improvement. The outcomes stay in their own units: LaplaceDiscreteSurrogate standardizes them itself.

seen = torch.randperm(len(candidates))[:10].tolist()

for i in range(10):
    model = LaplaceDiscreteSurrogate(
        Net(), [candidates[j] for j in seen], y[seen]
    )

    pending = [j for j in range(len(candidates)) if j not in seen]
    pred = model.predict([candidates[j] for j in pending])
    ei = expected_improvement(pred, best=y[seen].max())
    seen.append(pending[ei.argmax()])

    print(f"round {i + 1:2d}: best = {y[seen].max():.3f}")
round  1: best = 4.953
round  2: best = 4.953
round  3: best = 4.953
round  4: best = 4.953
round  5: best = 4.953
round  6: best = 4.953
round  7: best = 4.953
round  8: best = 5.137
round  9: best = 5.137
round 10: best = 5.383

We only do 10 rounds here so that the page runs quickly. In practice, BO runs for hundreds or thousands of rounds.

pred has the mean and the standard deviation per candidate, in the units of y. discrete_acqf also has upper_confidence_bound and thompson_sampling, and every function there takes maximize=False to minimize.

Batches

To evaluate several candidates per round, thompson_batch draws one function from the posterior per pick, and each draw picks its best candidate among those not picked yet.

pending = [j for j in range(len(candidates)) if j not in seen]
picks = thompson_batch(model, [candidates[j] for j in pending], q=4)
print([candidates[pending[k]] for k in picks])
['GCGCAA', 'GCGCCC', 'GGGCCA', 'GCGCAC']
TipTensor candidates

If the candidates are vectors, LaplaceDiscreteSurrogate takes them as a tensor, with no prepare. Alternatively, stay with BoTorch: LaplaceBoTorchSurrogate with optimize_acqf_discrete, as in Thompson sampling.

The network can also be a pretrained language model, for texts: see Language models.