true_probs_easy <- c(0.05, 0.08, 0.15, 0.11, 0.03)
true_probs_hard <- c(0.10, 0.12, 0.15, 0.14, 0.09)
trials <- 2000- 1
- シナリオ1の真のクリック率です。Arm 3 が最も高く 0.15 です。
- 2
- シナリオ2の真のクリック率です。Arm 3 の 0.15 に対し、Arm 4 が 0.14、Arm 2 が 0.12 と近い値です。
- 3
- インプレッションの合計回数です。
R, RStudio, Quarto and STEM(Science, Technology, Engineering and Mathematics)
R, A/Bテスト, 多腕バンディット問題, ε-Greedy, UCB, トンプソンサンプリング, ベータ分布, リグレット, シミュレーション, 強化学習, 統計
Rで A/Bテスト の発展形である 多腕バンディット問題 を試みます。ECサイトのバナー広告を題材に、ε-Greedy法、UCB、トンプソンサンプリング の3つの解法を実装し、シミュレーションで比べます。
あるECサイトが、新しいキャンペーンのためにトップページに表示するバナー広告を作りました。デザイン案は5つあり、どれが最もクリックされやすいかは分かりません。
通常のA/Bテストでは、各案を均等に表示してから、結果を比べます。ですので、効果の低い案も最後まで同じ回数だけ表示してしまい、得られたはずのクリックを逃します。多腕バンディット問題では、結果を学習しながら表示する案を切り替え、クリックの取りこぼし(機会損失)を抑えつつ、クリック率の高い案を見つけることを目指します。
1、クリックされなかったら 02000 回本記事のシミュレーションでは、各バナーの「真のクリック率」を先に決めておきます。ただし、アルゴリズムはこの値を知らず、表示した結果だけから学習します。真のクリック率の組は、次の2つのシナリオを用意します。
| バナー | シナリオ1 | シナリオ2 |
|---|---|---|
| Arm 1 | 0.05 | 0.10 |
| Arm 2 | 0.08 | 0.12 |
| Arm 3 | 0.15 | 0.15 |
| Arm 4 | 0.11 | 0.14 |
| Arm 5 | 0.03 | 0.09 |
どのシナリオでも、最適な腕を毎回選べたときの期待クリック数は、\(2000 \times 0.15 = 300\) です。この値が、各手法の総報酬の上限の目安になります。
3つの解法は、どれも「これまでの結果から次に表示する腕を選び、報酬を受け取り、結果を更新する」ことを trials 回繰り返します。そのため、最大値が複数あるときにその中から1つを選ぶ関数を、先に用意します。
sample() に長さ1の数値 \(k\) を渡すと、\(1\) から \(k\) までの整数から選んでしまいます。候補が1つのときも正しく返せるように、添字で選びます。
確率 \(\varepsilon\) でランダムに腕を選び(探索)、それ以外は、現時点で平均報酬が最も高い腕を選びます(活用)。腕 \(k\) の平均報酬は、報酬の合計を \(s_k\)、選んだ回数を \(n_k\) として、次の式で推定します。
\[ \hat{p}_k = \frac{s_k}{n_k} \]
epsilon_greedy <- function(true_probs, trials, epsilon = 0.1) {
arms <- length(true_probs)
counts <- rep(0, arms)
values <- rep(0, arms)
total_reward <- 0
rewards_history <- numeric(trials)
for (t in 1:trials) {
if (runif(n = 1, min = 0, max = 1) < epsilon) {
chosen_arm <- sample.int(arms, 1)
} else {
avg_values <- ifelse(counts > 0, values / counts, 0)
best_arms <- which(avg_values == max(avg_values))
chosen_arm <- choose_one(best_arms)
}
reward <- rbinom(1, 1, prob = true_probs[chosen_arm])
counts[chosen_arm] <- counts[chosen_arm] + 1
values[chosen_arm] <- values[chosen_arm] + reward
total_reward <- total_reward + reward
rewards_history[t] <- total_reward
}
list(
total_reward = total_reward,
rewards_history = rewards_history,
counts = counts
)
}「平均報酬」に「不確かさ」を足した UCBスコア が最も高い腕を選びます。不確かさは、選んだ回数が少ない腕ほど大きくなります。\(t\) 回目の試行での、腕 \(k\) のUCBスコアは次の式です。
\[ \mathrm{UCB}_k(t) = \hat{p}_k + \sqrt{\frac{c \ln t}{n_k}} \]
ここで \(c\) は探索の強さを決める定数で、本記事では \(c = 2\) とします。
ucb <- function(true_probs, trials, c_param = 2) {
arms <- length(true_probs)
counts <- rep(0, arms)
values <- rep(0, arms)
total_reward <- 0
rewards_history <- numeric(trials)
for (i in 1:arms) {
reward <- rbinom(1, 1, prob = true_probs[i])
counts[i] <- 1
values[i] <- reward
total_reward <- total_reward + reward
rewards_history[i] <- total_reward
}
for (t in (arms + 1):trials) {
avg_values <- values / counts
ucb_scores <- avg_values + sqrt(c_param * log(t) / counts)
chosen_arm <- choose_one(which(ucb_scores == max(ucb_scores)))
reward <- rbinom(1, 1, prob = true_probs[chosen_arm])
counts[chosen_arm] <- counts[chosen_arm] + 1
values[chosen_arm] <- values[chosen_arm] + reward
total_reward <- total_reward + reward
rewards_history[t] <- total_reward
}
list(
total_reward = total_reward,
rewards_history = rewards_history,
counts = counts
)
}各腕のクリック率を ベータ分布 で表し、その分布から乱数を1つずつ引いて、最も大きな値が出た腕を選びます。成功(クリック)の回数を \(s_k\)、失敗(クリックなし)の回数を \(f_k\) とすると、腕 \(k\) のクリック率 \(\theta_k\) は、事前分布を \(\mathrm{Beta}(1, 1)\)(一様分布)としたとき、次の分布に従うと考えます。
\[ \theta_k \sim \mathrm{Beta}(1 + s_k,\ 1 + f_k) \]
結果が増えるほど分布が狭まり、選ばれる腕が自然に絞られていきます。
thompson_sampling <- function(true_probs, trials) {
arms <- length(true_probs)
alpha <- rep(1, arms)
beta <- rep(1, arms)
total_reward <- 0
rewards_history <- numeric(trials)
for (t in 1:trials) {
sampled_probs <- rbeta(arms, alpha, beta)
chosen_arm <- choose_one(which(sampled_probs == max(sampled_probs)))
reward <- rbinom(1, 1, prob = true_probs[chosen_arm])
if (reward == 1) {
alpha[chosen_arm] <- alpha[chosen_arm] + 1
} else {
beta[chosen_arm] <- beta[chosen_arm] + 1
}
total_reward <- total_reward + reward
rewards_history[t] <- total_reward
}
list(
total_reward = total_reward,
rewards_history = rewards_history,
counts = alpha + beta - 2
)
}まず、シナリオ1で、3つの解法を1回ずつ実行します。乱数の種は公開日の 20250615 にします。
各腕を選んだ回数と総報酬は、次のとおりです(表 2)。
counts_table <- data.frame(
item = c(paste("Arm", 1:5), "総報酬"),
greedy = c(result_greedy$counts, result_greedy$total_reward),
ucb = c(result_ucb$counts, result_ucb$total_reward),
ts = c(result_ts$counts, result_ts$total_reward)
)
knitr::kable(
counts_table,
col.names = c("項目", method_labels),
align = "lrrr"
)| 項目 | ε-Greedy | UCB | トンプソン |
|---|---|---|---|
| Arm 1 | 40 | 300 | 32 |
| Arm 2 | 1847 | 337 | 284 |
| Arm 3 | 37 | 623 | 1313 |
| Arm 4 | 40 | 504 | 325 |
| Arm 5 | 36 | 236 | 46 |
| 総報酬 | 175 | 166 | 279 |
累積報酬の推移も確認します(図 1)。
library(ggplot2)
reward_data <- data.frame(
trial = rep(1:trials, times = 3),
method = factor(rep(method_labels, each = trials), levels = method_labels),
reward = c(
result_greedy$rewards_history,
result_ucb$rewards_history,
result_ts$rewards_history
)
)
ggplot(reward_data, aes(x = trial, y = reward, color = method)) +
geom_line() +
geom_abline(slope = max(true_probs_easy), intercept = 0, linetype = "dashed") +
labs(x = "インプレッション数", y = "累積報酬", color = "手法") +
theme_minimal()この1回では、ε-Greedy法は、序盤の結果から Arm 2 を最良と判断し、2000回中1847回も選び続けました。Arm 2 の真のクリック率は 0.08 で、最適な Arm 3 の 0.15 より低いため、総報酬は 175 にとどまりました。UCBは、Arm 3 を623回しか選ばず、総報酬は 166 でした。トンプソンサンプリングは、Arm 3 を1313回選び、総報酬は 279 で、上限の目安である 300 に近い値でした。ただし、これは1回の結果ですので、手法の優劣はまだ言えません。
1回の結果は、乱数によるばらつきを含みます。ですので、手法の性能を比べるために、同じ試験を 100回 繰り返します。各回の結果から、次の3つの指標を求めます。
\[ \text{擬似リグレット} = \sum_{k=1}^{5} n_k \left( p^* - p_k \right) \]
num_simulations <- 100
run_simulations <- function(probs, num_simulations, trials) {
algorithms <- list(
epsilon_greedy = epsilon_greedy,
ucb = ucb,
thompson_sampling = thompson_sampling
)
results <- lapply(names(algorithms), function(name) {
runs <- lapply(seq_len(num_simulations), function(i) {
algorithms[[name]](probs, trials)
})
data.frame(
simulation = seq_len(num_simulations),
algorithm = name,
total_reward = sapply(runs, function(r) r$total_reward),
regret = sapply(runs, function(r) sum(r$counts * (max(probs) - probs))),
best_rate = sapply(runs, function(r) r$counts[which.max(probs)] / trials)
)
})
results_df <- do.call(rbind, results)
results_df$algorithm <- factor(
results_df$algorithm,
levels = c("epsilon_greedy", "ucb", "thompson_sampling"),
labels = method_labels
)
results_df
}
set.seed(20250615)
results_easy <- run_simulations(true_probs_easy, num_simulations, trials)
results_hard <- run_simulations(true_probs_hard, num_simulations, trials)手法ごとに、100回の平均を求めます。
summarize_results <- function(results_df) {
results_df |>
dplyr::group_by(algorithm) |>
dplyr::summarise(
mean_reward = mean(total_reward),
se_reward = sd(total_reward) / sqrt(dplyr::n()),
mean_regret = mean(regret),
mean_best = mean(best_rate) * 100
) |>
knitr::kable(
digits = c(0, 1, 1, 1, 1),
col.names = c("手法", "平均総報酬", "標準誤差", "リグレット", "最適腕率(%)"),
align = "lrrrr"
)
}シナリオ1(差が明確な場合)の結果です(表 3)。
| 手法 | 平均総報酬 | 標準誤差 | リグレット | 最適腕率(%) |
|---|---|---|---|---|
| ε-Greedy | 259.5 | 3.6 | 39.9 | 64.7 |
| UCB | 206.8 | 1.7 | 93.3 | 36.9 |
| トンプソン | 265.2 | 2.1 | 31.6 | 75.8 |
シナリオ2(差が僅かな場合)の結果です(表 4)。
| 手法 | 平均総報酬 | 標準誤差 | リグレット | 最適腕率(%) |
|---|---|---|---|---|
| ε-Greedy | 272.4 | 2.7 | 28.1 | 43.6 |
| UCB | 247.5 | 1.6 | 50.2 | 25.7 |
| トンプソン | 270.3 | 1.9 | 30.0 | 43.3 |
平均総報酬と平均リグレットは、おおむね「平均総報酬 + 平均リグレット \(\approx\) 300」の関係にあります。総報酬が大きい手法ほど、リグレット(機会損失)は小さくなります。
総報酬のばらつきを、箱ひげ図で比べます。
シナリオ1の総報酬です(図 2)。
シナリオ2の総報酬です(図 3)。
100回のシミュレーションの結果は、次のとおりです。
UCBが低くなったのは、\(c = 2\) では不確かさの項が大きく、探索が長く続くためと考えられます。たとえば \(t = 2000\)、\(n_k = 400\) のとき、不確かさの項は定義式から計算すると \(\sqrt{2 \ln 2000 / 400} \approx 0.19\) で、腕の間のクリック率の差(0.01 から 0.12)より大きな値です。UCBの結果は、定数 \(c\) の選び方に左右されます。ε-Greedy法の \(\varepsilon\)、試行回数、真のクリック率の組を変えれば、手法の順位も変わり得ます。本記事の結論は、ここで設定した条件での結果です。