開始使用免費開始

實作完整的 DQN 演算法

終於到了這一步!所有前置條件都已經完成;你現在要實作完整的 DQN 演算法,並用它來訓練一個 Lunar Lander 智能體。這代表你的演算法不只會使用經驗回放(Experience Replay),還會用到遞減式 epsilon 貪婪(Decayed Epsilon-Greediness)與固定 Q 目標(Fixed Q-Targets)。

已提供實作遞減式 epsilon 貪婪的 select_action() 函式可供你使用,上一個練習中的 update_target_network() 函式也同樣可用。接下來只需要把這些函式接到 DQN 的訓練迴圈中,並確保在計算損失時正確使用目標網路即可。

你需要維護一個新的步數計數器 total_steps,用來隨時間遞減 \varepsilon 的值。這個變數已替你初始化為 0。

本練習屬於課程

Python 的深度強化學習

檢視課程

練習說明

  • 使用 select_action() 來實作遞減式 epsilon 貪婪並選出智能體的動作;你需要使用跨回合累計的 total_steps。
  • 在計算 TD 目標之前,先關閉梯度追蹤。
  • 取得下一個狀態後,計算該狀態的 Q 值。
  • 在每一步結尾更新目標網路。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

for episode in range(10):
    state, info = env.reset()
    done = False
    step = 0
    episode_reward = 0
    while not done:
        step += 1
        total_steps += 1
        q_values = online_network(state)
        # Select the action with epsilon greediness
        action = ____(____, ____, start=.9, end=.05, decay=1000)
        next_state, reward, terminated, truncated, _ = env.step(action)
        done = terminated or truncated
        replay_buffer.push(state, action, reward, next_state, done)        
        if len(replay_buffer) >= batch_size:
            states, actions, rewards, next_states, dones = replay_buffer.sample(64)
            q_values = online_network(states).gather(1, actions).squeeze(1)
            # Ensure gradients are not tracked
            with ____:
                # Obtain the next state Q-values
                next_q_values = ____(next_states).amax(1)
                target_q_values = rewards + gamma * next_q_values * (1-dones)
            loss = nn.MSELoss()(q_values, target_q_values)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()   
            # Update the target network weights
            ____(____, ____, tau=.005)
        state = next_state
        episode_reward += reward    
    describe_episode(episode, reward, episode_reward, step)
編輯並執行程式碼