Multi-armed bandits solved a multi-armed bandit with \(\epsilon\)-greedy and Thompson sampling. This example solves a 10-armed bandit with a soft-max policy instead. It follows the example in Deep Reinforcement Learning in Action.
The bandit
Each of the 10 arms has a probability \(p_i\), drawn uniformly from \([0, 1]\) at the start. Pulling arm \(i\) gives a reward of 1 plus one for each of 10 trials that succeeds with probability \(p_i\), so its expected reward is \(1 + 10 p_i\). The agent does not know the \(p_i\). It keeps, for every arm, how often it pulled it and the mean reward it got from it.
The soft-max policy
Always pulling the arm with the best mean so far never tries the others, and an arm that was unlucky at first is never tried again. A soft-max policy picks every arm with a probability that grows with its mean reward \(Q_i\),
\[P(i) = \frac{e^{Q_i / \tau}}{\sum_{j} e^{Q_j / \tau}} ,
\]
where the temperature \(\tau\), 0.7 here, sets how strongly it favours the best arms. A large \(\tau\) picks the arms almost uniformly; a small one almost always picks the best. bitrl::maths::softmax_vec computes the probabilities, and a std::discrete_distribution picks an arm from them.
Every arm's mean starts at 11, the largest reward an arm can pay. Started at 0, the first arm that paid anything would have a mean so far above the untried arms that the policy would pull it for ever. Started at the largest reward, every untried arm looks as good as any can be until it is tried, so each is tried early.
What it writes
The example runs 500 pulls. After each one it prints the mean reward of all the pulls so far, and at the end it writes these means to rewards.csv, one per line, in the directory it runs from. It also writes pulls.csv: the success probability of every arm, then the arm and the reward of every pull.
The results
|
| How often the soft-max policy pulled every arm, every 10 pulls. The best arm is orange. |
The best arm, 4, succeeds with probability 0.91, but arms 0, 3 and 7 are close behind at 0.84, 0.80 and 0.77, so the policy keeps pulling them too: in 500 pulls arm 4 got 237, arm 3 127, arm 0 79 and arm 7 48, and the other six one to four each. Among them is arm 2, at 0.78 as good as arm 7: a poor first reward lowered its mean below the others', and the soft-max rarely tried it again. Lowering \(\tau\) makes such arms rarer still; raising it spreads the pulls over the poor arms as well. The mean reward of the 500 pulls was 9.58, against the best arm's 10.1. examples/tools/bandit_gif.py draws pulls.csv:
python examples/tools/bandit_gif.py pulls.csv --every 10 --out softmax_bandits.gif
The driver code
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <numeric>
#include <random>
#include <tuple>
#include <utility>
{
{
auto reward = 1;
for (
uint_t i = 0; i < n; ++i)
{
auto prob_value =
static_cast<real_t>(rand()) /
static_cast<real_t>(RAND_MAX);
if (prob_value < prob)
{
reward += 1;
}
}
}
{
auto new_r = (records[
action][0] * records[
action][1] + r) / (records[action][0] + 1);
}
{
std::vector<real_t>
values(records.size(), 0.0);
for (
uint_t i = 0; i < records.size(); ++i)
{
}
auto iterator_result = std::max_element(
values.begin(),
values.end());
return std::distance(
values.begin(), iterator_result);
}
{
std::vector<real_t> probs(n);
for (
uint_t i = 0; i < n; ++i)
{
probs[i] =
static_cast<real_t>(rand()) /
static_cast<real_t>(RAND_MAX);
}
return probs;
}
{
auto counter = 0;
for (auto item : values)
{
vec[counter++] = item[1];
}
return vec;
}
}
{
std::vector<std::vector<real_t>> records(
N);
{
}
std::vector<real_t> rewards;
std::vector<uint_t> arms;
std::vector<real_t> pulled;
{
std::cout << "Running experiment: " << i + 1 << std::endl;
std::discrete_distribution<> distribution(p.begin(), p.end());
auto choice = distribution(gen);
arms.push_back(choice);
pulled.push_back(r);
if (!rewards.empty())
{
auto mean_reward = ((i + 1) * rewards.back() + r) / (i + 2);
rewards.push_back(mean_reward);
}
else
{
rewards.push_back(r);
}
std::cout << "\tReward obtained: " << rewards[i] << std::endl;
}
{
std::ofstream file("pulls.csv");
file << "# p";
for (auto p : probs)
{
file << "," << p;
}
file << "\n# method,pull,arm,reward\n";
for (
uint_t i = 0; i < arms.size(); ++i)
{
file << "soft-max," << i << "," << arms[i] << "," << pulled[i] << "\n";
}
}
csv_writer.open();
csv_writer.write_column_vector(rewards);
csv_writer.close();
return 0;
}
The CSVWriter class. Handles writing into CSV file format.
Definition csv_file_writer.h:22
int main()
Definition discounted_returns.cpp:19
uint_t choice(const Vec2 &probs, uint_t seed=42)
choice. Implements similar functionality to numpy.choice function
Definition vector_math.h:181
std::vector< T > softmax_vec(const std::vector< T > &vec, real_t tau=1.0)
applies softmax operation to the elements of the vector and returns a vector with the result
Definition vector_math.h:313
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
Eigen::RowVectorX< T > DynVec
Dynamically sized row vector.
Definition bitsim_types.h:101
void record(const std::vector< Run > &runs, const std::string &directory)
Definition cart_pole_lqr_mpc.cpp:194
Definition markov_chain.cpp:11
void update_record(std::vector< std::vector< real_t > > &records, uint_t action, real_t r)
Definition softmax_bandits.cpp:64
std::vector< real_t > get_probs(uint_t n)
Definition softmax_bandits.cpp:85
const auto TAU
Definition softmax_bandits.cpp:42
uint_t get_best_arm(const std::vector< std::vector< real_t > > &records)
Definition softmax_bandits.cpp:72
const uint_t N
Definition softmax_bandits.cpp:33
const auto N_EXPERIMENTS
Definition softmax_bandits.cpp:36
const real_t MAX_REWARD
Definition softmax_bandits.cpp:39
real_t get_reward(real_t prob, uint_t n=10)
Definition softmax_bandits.cpp:47
const uint SEED
Definition softmax_bandits.cpp:45
DynVec< real_t > extract_part(const std::vector< std::vector< real_t > > &values)
Definition softmax_bandits.cpp:98
dict action
Definition play.py:46
reward
Definition play.py:49
list values
Definition plot_losses.py:13