บรรลุเป้าหมายได้ดีและเร็วขึ้น
SARSA(λ), Q(λ), Dyna-Q: ใช้ข้อมูลให้คุ้มขึ้น
บทนี้ทำให้ agent ใช้ข้อมูลคุ้มค่าขึ้นด้วย 2 ทาง: ส่ง credit เร็วขึ้น และเรียน model แล้ววางแผน
ในโค้ด Dyna-Q: หลังเจอเป้าหมายครั้งแรก การวางแผน 20 รอบต่อก้าวช่วยส่งรางวัลกลับเร็วมาก แค่เกมถัดมา agent ก็เดินเส้นทางที่สั้นที่สุด (6 ก้าว) ได้แล้ว
ส่ง credit เร็วขึ้น: SARSA(λ), Q(λ)ใช้ eligibility traces ส่งรางวัลกลับไปยังหลาย state ที่ผ่านมาพร้อมกัน
เรียน model แล้ววางแผน: Dyna-Qจำว่า "ทำ a ใน s แล้วไป s' ได้ r" แล้วใช้ model นี้อัปเดต Q เพิ่ม โดยไม่ต้องเล่นจริง
Trajectory sampling คล้าย Dyna-Q แต่จินตนาการเป็นเส้นทางต่อเนื่องจาก state ปัจจุบัน วิธี model-based เหมาะกับงานที่เก็บข้อมูลแพง เช่น หุ่นยนต์จริง
สิ่งที่ควรจำ
- Effective = แก้ปัญหาได้, Efficient = ใช้ข้อมูลน้อย
- บทต่อไปเพิ่ม "สุ่ม": state มากจนเห็นไม่ครบ
import numpy as np
import gymnasium as gym
env = gym.make("FrozenLake-v1", is_slippery=False)
n_s, n_a = env.observation_space.n, env.action_space.n
Q = np.zeros((n_s, n_a))
model = {} # (s, a) -> (r, s2, term) ໂມເດວທີ່ຮຽນຈາກປະສົບການ
rng = np.random.default_rng(0)
gamma, alpha, eps, n_planning = 0.95, 0.5, 0.1, 20
def update(s, a, r, s2, term):
target = r + gamma * Q[s2].max() * (not term)
Q[s, a] += alpha * (target - Q[s, a])
for ep in range(30):
s, _ = env.reset(seed=ep)
done, steps = False, 0
while not done:
if rng.random() < eps or Q[s].max() == Q[s].min():
a = rng.integers(n_a)
else:
a = int(np.argmax(Q[s]))
s2, r, term, trunc, _ = env.step(a)
update(s, a, r, s2, term) # 1) ຮຽນຈາກປະສົບການຈິງ
model[(s, a)] = (r, s2, term) # 2) ບັນທຶກລົງໂມເດວ
keys = list(model)
for _ in range(n_planning): # 3) "ຈິນຕະນາການ" ຈາກໂມເດວ
ps, pa = keys[rng.integers(len(keys))]
update(ps, pa, *model[(ps, pa)])
s, done, steps = s2, term or trunc, steps + 1
if r == 1:
print(f"ເກມທີ {ep:2d}: ໄປຮອດເປົ້າໝາຍໃນ {steps} ກ້າວ")
ผลลัพธ์
ເກມທີ 20: ໄປຮອດເປົ້າໝາຍໃນ 43 ກ້າວ ເກມທີ 21: ໄປຮອດເປົ້າໝາຍໃນ 7 ກ້າວ ເກມທີ 22: ໄປຮອດເປົ້າໝາຍໃນ 6 ກ້າວ ເກມທີ 23: ໄປຮອດເປົ້າໝາຍໃນ 6 ກ້າວ ເກມທີ 24: ໄປຮອດເປົ້າໝາຍໃນ 6 ກ້າວ ເກມທີ 25: ໄປຮອດເປົ້າໝາຍໃນ 6 ກ້າວ ເກມທີ 26: ໄປຮອດເປົ້າໝາຍໃນ 7 ກ້າວ ເກມທີ 28: ໄປຮອດເປົ້າໝາຍໃນ 6 ກ້າວ ເກມທີ 29: ໄປຮອດເປົ້າໝາຍໃນ 6 ກ້າວ
- #DeepRL
- #ReinforcementLearning
- #PythonສຳລັບຄົນLaos
- #AI
- #ບອກຕໍ່ຄວາມຮູ້