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

ฟังก์ชัน Loss ของ DQN แบบพื้นฐาน

เมื่อฟังก์ชัน select_action() พร้อมใช้งานแล้ว ขั้นตอนสุดท้ายก่อนที่จะเทรน agent ได้คือการ implement calculate_loss()

ฟังก์ชัน calculate_loss() คืนค่า loss ของโครงข่ายในแต่ละ step ของ episode

สูตร loss มีดังนี้:

ข้อมูลตัวอย่างต่อไปนี้ถูกโหลดไว้ในแบบฝึกหัดแล้ว:

state = torch.rand(8)
next_state = torch.rand(8)
action = select_action(q_network, state)
reward = 1
gamma = .99
done = False

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

Deep Reinforcement Learning ด้วย Python

ดูคอร์ส

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

  • หา Q-value ของสถานะปัจจุบัน
  • หา Q-value ของสถานะถัดไป
  • คำนวณ Q-value เป้าหมาย หรือ TD-target
  • คำนวณฟังก์ชัน loss นั่นคือ Squared Bellman Error

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

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

def calculate_loss(q_network, state, action, next_state, reward, done):
    q_values = q_network(state)
    print(f'Q-values: {q_values}')
    # Obtain the current state Q-value
    current_state_q_value = q_values[____]
    print(f'Current state Q-value: {current_state_q_value:.2f}')
    # Obtain the next state Q-value
    next_state_q_value = q_network(next_state).____    
    print(f'Next state Q-value: {next_state_q_value:.2f}')
    # Calculate the target Q-value
    target_q_value = ____ + gamma * ____ * (1-done)
    print(f'Target Q-value: {target_q_value:.2f}')
    # Obtain the loss
    loss = nn.MSELoss()(____, ____)
    print(f'Loss: {loss:.2f}')
    return loss

calculate_loss(q_network, state, action, next_state, reward, done)
แก้ไขและรันโค้ด