Temporal difference learning

Reinforcement Learning with Gymnasium ใน Python

Fouad Trad

Machine Learning Engineer

TD learning vs. Monte Carlo

 

TD learning
  • ไม่ใช้โมเดล
  • ประมาณค่า Q-table จากการโต้ตอบกับสภาพแวดล้อม
  • อัปเดต Q-table ทุกขั้นตอนภายใน episode
  • เหมาะกับงานที่มี episode ยาวหรือไม่มีจุดสิ้นสุดชัดเจน

 

Monte Carlo
  • ไม่ใช้โมเดล
  • ประมาณค่า Q-table จากการโต้ตอบกับสภาพแวดล้อม
  • อัปเดต Q-table เมื่อจบ episode อย่างน้อยหนึ่งครั้ง
  • เหมาะกับงานที่มี episode สั้น
Reinforcement Learning with Gymnasium ใน Python

TD learning กับการพยากรณ์อากาศ

ภาพแสดงสภาพอากาศที่แตกต่างกันในเวลาต่างกันของสถานที่เดียวกัน

Reinforcement Learning with Gymnasium ใน Python

SARSA

  • อัลกอริทึม TD
  • วิธี on-policy: ปรับกลยุทธ์ตามการกระทำที่เลือกใช้จริง

ภาพแสดงว่า SARSA ย่อมาจาก state ปัจจุบัน action ที่เลือก reward ที่ได้รับ next state ที่สังเกต และ next action

Reinforcement Learning with Gymnasium ใน Python

กฎการอัปเดต SARSA

ภาพแสดงสูตรทางคณิตศาสตร์ของกฎการอัปเดต SARSA

  • $\alpha$: อัตราการเรียนรู้
  • $\gamma$: discount factor
  • ทั้งคู่มีค่าระหว่าง 0 ถึง 1
Reinforcement Learning with Gymnasium ใน Python

Frozen Lake

ภาพแสดงสภาพแวดล้อม Frozen Lake

Reinforcement Learning with Gymnasium ใน Python

การตั้งค่าเริ่มต้น

env = gym.make("FrozenLake", is_slippery=False)

num_states = env.observation_space.n num_actions = env.action_space.n
Q = np.zeros((num_states, num_actions))
alpha = 0.1 gamma = 1 num_episodes = 1000
Reinforcement Learning with Gymnasium ใน Python

ลูป SARSA

for episode in range(num_episodes):

state, info = env.reset() action = env.action_space.sample()
terminated = False while not terminated: next_state, reward, terminated, truncated, info = env.step(action)
next_action = env.action_space.sample()
update_q_table(state, action, reward, next_state, next_action)
state, action = next_state, next_action
Reinforcement Learning with Gymnasium ใน Python

การอัปเดต SARSA

def update_q_table(state, action, reward, next_state, next_action):

old_value = Q[state, action]
next_value = Q[next_state, next_action]
Q[state, action] = (1 - alpha) * old_value + alpha * (reward + gamma * next_value)

  ภาพแสดงสูตรทางคณิตศาสตร์ของกฎการอัปเดต SARSA

Reinforcement Learning with Gymnasium ใน Python

การหา policy ที่ดีที่สุด

policy = get_policy()
print(policy)
{ 0: 1,  1: 2,  2: 1,  3: 0, 
  4: 1,  5: 0,  6: 1,  7: 0, 
  8: 2,  9: 1, 10: 1, 11: 0, 
 12: 0, 13: 2, 14: 2, 15: 0}

ภาพแสดง policy ที่ดีที่สุดในสภาพแวดล้อม Frozen Lake โดยใช้ลูกศรแทน action และเห็นได้ว่า agent หลีกเลี่ยงการตกลงในหลุม

Reinforcement Learning with Gymnasium ใน Python

มาฝึกกันเถอะ!

Reinforcement Learning with Gymnasium ใน Python

Preparing Video For Download...