权衡探索与利用
有很多台老虎机,该选哪一台?
不知道 MDP 时,agent 只能看到 +1、−4 这样的奖励数字,因此永远不知道是否还藏着更好的选择。
这就是“探索与利用”问题。因为没选最好的选项而损失的奖励称为后悔值(regret)。
代码中,纯贪心策略会卡在最先遇到的那台机器上,而 UCB 利用不确定性来选择,更接近最佳平均值。
| 策略 | 思路 |
|---|---|
| ε-greedy | 大多数时候选最好的,以概率 ε 随机选择 |
| Decaying ε-greedy | 开始时多探索,然后逐渐减小 ε |
| Optimistic initialization | 把 Q 的初始值设得很高,迫使每个选项都被尝试 |
| Softmax | 按 Q 值的比例随机选择 |
| UCB | 给尝试较少的选项加上“不确定性奖励” |
| Thompson sampling | 从每个选项的贝叶斯信念分布中采样 |
要点
- 不探索 = 可能困在差的选择上;探索过多 = 浪费奖励
- 好的策略会利用“不确定性”,而不是盲目随机
import numpy as np
rng = np.random.default_rng(0)
true_means = rng.normal(0, 1, size=10) # ເຄື່ອງ slot 10 ເຄື່ອງ (ບໍ່ຮູ້ຄ່າຈິງ)
def run(strategy, steps=1000):
Q, N, total = np.zeros(10), np.zeros(10), 0.0
for t in range(1, steps + 1):
a = strategy(Q, N, t)
r = rng.normal(true_means[a], 1)
N[a] += 1
Q[a] += (r - Q[a]) / N[a] # ຄ່າສະເລ່ຍແບບ incremental
total += r
return total / steps
def epsilon_greedy(Q, N, t, eps=0.1):
return rng.integers(10) if rng.random() < eps else int(np.argmax(Q))
def ucb(Q, N, t, c=2.0):
if (N == 0).any():
return int(np.argmin(N)) # ລອງທຸກເຄື່ອງກ່ອນ
return int(np.argmax(Q + c * np.sqrt(np.log(t) / N)))
print(f"ຄ່າສູງສຸດທີ່ເປັນໄປໄດ້ : {true_means.max():.3f}")
print(f"greedy (eps=0) : {run(lambda Q, N, t: epsilon_greedy(Q, N, t, 0)):.3f}")
print(f"epsilon-greedy (0.1) : {run(epsilon_greedy):.3f}")
print(f"UCB : {run(ucb):.3f}")
输出结果
ຄ່າສູງສຸດທີ່ເປັນໄປໄດ້ : 1.304 greedy (eps=0) : 0.642 epsilon-greedy (0.1) : 1.039 UCB : 1.195
- #DeepRL
- #ReinforcementLearning
- #PythonສຳລັບຄົນLaos
- #AI
- #ບອກຕໍ່ຄວາມຮູ້