Chuyển đến nội dung chính

第 4 課:Q-Learning 深入研究與多臂 Bandits

Q-Learning 演算法詳細資訊。 ε-貪婪探索。多臂強盜問題。 UCB,湯普森採樣。實踐計程車環境。

🧠 人工智慧與機器學習 — 第 3 課 第 4 課:Q-Learning 深入研究與多臂訓練 土匪

強化學習:從基礎到高級

第 1 部分:強化學習基礎 — 馬可夫決策過程與表格方法

亞洲開發網

簡介

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}")

總結

戰略優勢缺點
ε-貪婪簡單、有效統一隨機探索
ε-衰變平衡探索/利用需要調整衰減率
聯合銀行有原則,沒有ε確定性
湯普森貝葉斯最優計算成本
波茲曼平穩、溫控對規模敏感