Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add thompson sampling #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions generate_plots.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
# python algorithms/softmax/test_annealing.py
# python algorithms/ucb/test_ucb1.py
# python algorithms/exp3/test_exp3.py
# python algorithms/ts/test_thompson_sampling.py
# cd ..

# Use R for generating graphs
Expand Down
20 changes: 20 additions & 0 deletions python/algorithms/ts/test_thompson_sampling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
execfile("core.py")

import random

random.seed(1)
means = [0.1, 0.1, 0.1, 0.1, 0.9]
n_arms = len(means)
random.shuffle(means)
arms = map(lambda (mu): BernoulliArm(mu), means)
print("Best arm is " + str(ind_max(means)))

f = open("algorithms/ts/thompson_sampling_results.csv", "w")

algo = ThompsonSampling(1,1, [], [], [])
algo.initialize(n_arms)
results = test_algorithm(algo, arms, 5000, 250)
for i in range(len(results[0])):
f.write(",".join([str(results[j][i]) for j in range(len(results))]) + "\n")

f.close()
36 changes: 36 additions & 0 deletions python/algorithms/ts/thompson_sampling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import random

def ind_max(x):
m = max(x)
return x.index(m)

class ThompsonSampling():
def __init__(self, initial_alpha, initial_beta, counts, values, s_counts):
self.counts = counts
self.s_counts = s_counts
self.values = values
self.alpha = initial_alpha
self.beta = initial_beta
return

def initialize(self, n_arms):
self.counts = [0 for col in range(n_arms)]
self.values = [0.0 for col in range(n_arms)]
self.s_counts = [0 for col in range(n_arms)]
return

def select_arm(self):
rho = lambda i:random.betavariate(self.alpha + self.s_counts[i], self.beta + self.counts[i] - self.s_counts[i])
mu = map(rho, range(len(self.counts)))
return ind_max(mu);

def update(self, chosen_arm, reward):
self.counts[chosen_arm] = self.counts[chosen_arm] + 1
if reward == 1:
self.s_counts[chosen_arm] += 1

n = self.counts[chosen_arm]
value = self.values[chosen_arm]
new_value = ((n - 1) / float(n)) * value + (1 / float(n)) * reward
self.values[chosen_arm] = new_value
return
1 change: 1 addition & 0 deletions python/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def ind_max(x):
from algorithms.ucb.ucb2 import *
from algorithms.exp3.exp3 import *
from algorithms.hedge.hedge import *
from algorithms.ts.thompson_sampling import *

# # Testing framework
from testing_framework.tests import *
52 changes: 52 additions & 0 deletions r/ts/plot_thompson_sampling.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
library("plyr")
library("ggplot2")

results <- read.csv("python/algorithms/ts/thompson_sampling_results.csv", header = FALSE)
names(results) <- c("Sim", "T", "ChosenArm", "Reward", "CumulativeReward")

# Plot average reward as a function of time.
stats <- ddply(results,
c("T"),
function (df) {mean(df$Reward)})
ggplot(stats, aes(x = T, y = V1)) +
geom_line() +
ylim(0, 1) +
xlab("Time") +
ylab("Average Reward") +
ggtitle("Performance of the Thompson Sampling Algorithm")
ggsave("r/graphs/ts_average_reward.pdf")

# Plot frequency of selecting correct arm as a function of time.
# In this instance, 5 is the correct arm.
stats <- ddply(results,
c("T"),
function (df) {mean(df$ChosenArm == 1)})
ggplot(stats, aes(x = T, y = V1)) +
geom_line() +
ylim(0, 1) +
xlab("Time") +
ylab("Probability of Selecting Best Arm") +
ggtitle("Accuracy of the Thompson Sampling Algorithm")
ggsave("r/graphs/ts_average_accuracy.pdf")

# Plot variance of chosen arms as a function of time.
stats <- ddply(results,
c("T"),
function (df) {var(df$ChosenArm)})
ggplot(stats, aes(x = T, y = V1)) +
geom_line() +
xlab("Time") +
ylab("Variance of Chosen Arm") +
ggtitle("Variability of the Thompson Sampling Algorithm")
ggsave("r/graphs/ts_variance_choices.pdf")

# Plot cumulative reward as a function of time.
stats <- ddply(results,
c("T"),
function (df) {mean(df$CumulativeReward)})
ggplot(stats, aes(x = T, y = V1)) +
geom_line() +
xlab("Time") +
ylab("Cumulative Reward of Chosen Arm") +
ggtitle("Cumulative Reward of the Thompson Sampling Algorithm")
ggsave("r/graphs/ts_cumulative_reward.pdf")