1. Go to this page and download the library: Download cleatsquad/php-bandit library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cleatsquad / php-bandit example snippets
use CleatSquad\Bandit\ArmState;
use CleatSquad\Bandit\ThompsonSamplingPolicy;
$policy = new ThompsonSamplingPolicy();
$arms = [
'variant_a' => new ArmState(successes: 12, failures: 4),
'variant_b' => new ArmState(successes: 30, failures: 1),
];
$result = $policy->select($arms);
$result->selectedArm; // 'variant_b' — usually, but not always
$result->sample; // 0.9412... the draw that won
$result->samples; // every draw: ['variant_a' => 0.7318..., 'variant_b' => 0.9412...]
// 1. select — the library decides, from state you hand it
$arms = $yourStorage->loadArms(); // array<string, ArmState>
$result = $policy->select($arms);
// 2. execute — outside the library: serve the variant, call the provider…
$outcome = $yourSystem->run($result->selectedArm);
// 3. observe — reduce the outcome to a binary success or failure
$succeeded = $outcome->isSuccess();
// 4. update — immutable transition, always on the arm that played
$updated = $succeeded
? $arms[$result->selectedArm]->withSuccess()
: $arms[$result->selectedArm]->withFailure();
// 5. persist — outside the library: yours to write (see below)
$yourStorage->save($result->selectedArm, $updated);
$policy->posteriorMean(10, 2); // 0.846 — expected success rate
$policy->posteriorVariance(10, 2); // how unsure that estimate is
$policy->posteriorWeight(10, 2); // 0.0..1.0 confidence, 0 when uninformed
$policy->sample(10, 2); // one random draw from Beta(11, 3)
$policy = ThompsonSamplingPolicy::withSeed(42);
$policy->sample(5, 2); // same value on every run, for tests and simulations
$policy->selectBestArm($arms); // gone in 1.0.0
$policy->selectArm($arms); // same decision, honest name
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.