เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การ implement อัลกอริทึม DQN แบบสมบูรณ์

ถึงเวลาแล้ว! เมื่อทุกส่วนประกอบพร้อมแล้ว ขั้นตอนต่อไปคือการ implement อัลกอริทึม DQN แบบสมบูรณ์ และนำไปฝึก agent สำหรับ Lunar Lander ซึ่งหมายความว่าอัลกอริทึมนี้จะใช้ทั้ง Experience Replay, Decayed Epsilon-Greediness และ Fixed Q-Targets

ฟังก์ชัน select_action() ที่ implement Decayed Epsilon Greediness และฟังก์ชัน update_target_network() จากแบบฝึกหัดก่อนหน้าพร้อมใช้งานแล้ว สิ่งที่ต้องทำคือนำฟังก์ชันเหล่านี้เข้าไปใส่ใน training loop ของ DQN และตรวจสอบว่าใช้ Target Network ในการคำนวณ loss ได้อย่างถูกต้อง

ต้องสร้างตัวนับ step ใหม่ชื่อ total_steps เพื่อลดค่า \(\varepsilon\) ลงตามเวลา ตัวแปรนี้ถูกกำหนดค่าเริ่มต้นเป็น 0 ให้แล้ว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Deep Reinforcement Learning ด้วย Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ใช้ select_action() เพื่อ implement Decayed Epsilon Greediness และเลือก action ของ agent โดยต้องใช้ total_steps ซึ่งเป็นผลรวมของ steps ทั้งหมดในทุก episode
  • ก่อนคำนวณ TD target ให้ปิดการติดตาม gradient
  • หลังจากได้ next state แล้ว ให้ดึงค่า Q-Values ของ next state
  • อัปเดต target network ที่ปลายแต่ละ step

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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)
แก้ไขและรันโค้ด