جواب «Step 2: The Experience Notebook» چالش 2 از جلسهی 20
سؤال
قدم ۲. حالا ربات خودش تصمیم بگیرد. اضافه کن:
- alpha = 0.5 و جدول Q: برای هر حالت ۰ تا ۴ یک دیکشنری {"jump": 0, "wait": 0}.
- best_action(s): اگر Q[s]["jump"] > Q[s]["wait"] بود "jump"، وگرنه "wait".
- learn(s, action, reward, new_dist, done): هدف target = reward است؛ اگر دور تمام نشده، بهترین عدد حالت بعد هم به آن اضافه شود. بعد Q[s][action] += alpha * (target - Q[s][action]).
در tick به جای قانون dist <= 2 از best_action استفاده کن و بعد از simulate تابع learn را صدا بزن. جدول را هم روی صفحه بنویس. ببین چند دور طول میکشد تا یاد بگیرد!
راهنما
حالت بعد s2 = state_of(new_dist) است و بهترین عددش max(Q[s2]["jump"], Q[s2]["wait"]). در tick اول s = state_of(dist) را نگه دار، چون dist عوض میشود.
یک جواب درست
import pgzrun
WIDTH = 600
HEIGHT = 300
TITLE = "Learning Runner"
dist = 10
jumping = False
message = ""
runner = Actor("robot", (80, 200))
rock = Actor("rock", (530, 200))
alpha = 0.5
def state_of(dist):
return (dist - 1) // 2
def simulate(dist, action):
if action == "jump":
if dist <= 2:
return 0, 10, True
return dist - 2, -1, False
dist = dist - 1
if dist == 0:
return 0, -10, True
return dist, 0, False
Q = {}
for s in range(5):
Q[s] = {"jump": 0, "wait": 0}
def best_action(s):
if Q[s]["jump"] > Q[s]["wait"]:
return "jump"
return "wait"
def learn(s, action, reward, new_dist, done):
target = reward
if not done:
s2 = state_of(new_dist)
target = reward + max(Q[s2]["jump"], Q[s2]["wait"])
Q[s][action] += alpha * (target - Q[s][action])
def tick():
global dist, jumping, message
s = state_of(dist)
action = best_action(s)
jumping = action == "jump"
new_dist, reward, done = simulate(dist, action)
learn(s, action, reward, new_dist, done)
dist = new_dist
if done:
message = "cleared!" if reward > 0 else "crash!"
dist = 10
def draw():
screen.fill("skyblue")
screen.draw.filled_rect(Rect(0, 225, 600, 75), "darkgreen")
runner.y = 130 if jumping else 200
rock.x = 80 + dist * 45
runner.draw()
rock.draw()
screen.draw.text("distance: " + str(dist) + " state: " + str(state_of(dist)), (10, 10), fontsize=28, color="black")
screen.draw.text(message, (10, 40), fontsize=28, color="darkred")
for s in range(5):
row = "state " + str(s) + ": jump " + str(round(Q[s]["jump"], 1)) + " wait " + str(round(Q[s]["wait"], 1))
screen.draw.text(row, (330, 10 + s * 22), fontsize=22, color="navy")
clock.schedule_interval(tick, 0.5)
pgzrun.go()
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن