簡介
Q-Learning 是離策略 TD 控制演算法 - DQN 和所有基於值的深度 RL 的基礎。 多臂強盜是一種簡化的強化學習,專注於探索與利用。
1.Q-Learning演算法
def q_learning(env, num_episodes, alpha=0.1, gamma=0.99, epsilon=0.1):
Q = np.zeros((env.observation_space.n, env.action_space.n))
for episode in range(num_episodes):
state, _ = env.reset()
done = False
while not done:
# ε-greedy action selection
if np.random.random() < epsilon:
action = env.action_space.sample()
else:
action = np.argmax(Q[state])
next_state, reward, terminated, truncated, _ = env.step(action)
done = terminated or truncated
# Q-Learning update (off-policy: max over next actions)
Q[state, action] += alpha * (
reward + gamma * np.max(Q[next_state]) * (1 - done) - Q[state, action]
)
state = next_state
return Q
SARSA 與 Q-Learning
| 非典 | Q-學習 | |
|---|---|---|
| 類型 | 在保政策 | 政策外 |
| 更新 | Q(s,a) += α[r + γQ(s',a') - Q(s,a)] | Q(s,a) += α[r + γ max Q(s',·) - Q(s,a)] |
| 行為 | 更安全,遵循 ε-貪婪 | 學習最優策略 |
2. 探索策略
ε-貪婪衰變
def epsilon_greedy_decay(Q, state, episode, min_epsilon=0.01, decay=0.995):
epsilon = max(min_epsilon, 1.0 * (decay ** episode))
if np.random.random() < epsilon:
return env.action_space.sample()
return np.argmax(Q[state])
玻爾茲曼(Softmax)探索
def boltzmann_action(Q, state, temperature=1.0):
q_values = Q[state] / temperature
probs = np.exp(q_values - np.max(q_values))
probs /= probs.sum()
return np.random.choice(len(probs), p=probs)
3. 多臂強盜
簡化的 RL:1 個狀態,K 個動作(武器),最大化獎勵。
class MultiArmedBandit:
def __init__(self, k=10):
self.k = k
self.true_values = np.random.randn(k)
def pull(self, arm):
return np.random.randn() + self.true_values[arm]
class UCBAgent:
def __init__(self, k, c=2.0):
self.counts = np.zeros(k)
self.values = np.zeros(k)
self.c = c
self.t = 0
def select_arm(self):
self.t += 1
if 0 in self.counts:
return np.argmin(self.counts)
ucb = self.values + self.c * np.sqrt(np.log(self.t) / self.counts)
return np.argmax(ucb)
def update(self, arm, reward):
self.counts[arm] += 1
self.values[arm] += (reward - self.values[arm]) / self.counts[arm]
4. 實踐:計程車環境
env = gym.make("Taxi-v3")
Q = q_learning(env, num_episodes=10000, alpha=0.1, gamma=0.99, epsilon=0.1)
# Test learned policy
state, _ = env.reset()
total_reward = 0
for _ in range(200):
action = np.argmax(Q[state])
state, reward, done, _, _ = env.step(action)
total_reward += reward
if done:
break
print(f"Total reward: {total_reward}")
總結
| 戰略 | 優勢 | 缺點 |
|---|---|---|
| ε-貪婪 | 簡單、有效 | 統一隨機探索 |
| ε-衰變 | 平衡探索/利用 | 需要調整衰減率 |
| 聯合銀行 | 有原則,沒有ε | 確定性 |
| 湯普森 | 貝葉斯最優 | 計算成本 |
| 波茲曼 | 平穩、溫控 | 對規模敏感 |