實作 SARSA 更新規則
SARSA 是 RL 中的 on-policy 演算法,會根據當前執行的動作,以及在下一個狀態所選擇的動作,來更新行動價值函式。這種作法不只學習當前的狀態-動作組合的價值,也同時考量接續的組合,因而能學到會顧及未來動作的策略。以下是 SARSA 的更新規則,你的任務是依據此規則,實作一個用來更新 Q 表的函式。
NumPy 函式庫已經以 np 名稱匯入。

本練習屬於課程
使用 Python 的 Gymnasium 進行強化學習
練習說明
- 取得給定狀態-動作組合的當前 Q 值。
- 找出下一個狀態-動作組合的 Q 值。
- 使用 SARSA 公式更新當前狀態-動作組合的 Q 值。
- 在代理於狀態
0執行動作0、獲得獎勵5、移動到狀態1,並執行動作1的情境下,更新 Q 表Q。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def update_q_table(state, action, reward, next_state, next_action):
# Get the old value of the current state-action pair
old_value = ____
# Get the value of the next state-action pair
next_value = ____
# Compute the new value of the current state-action pair
Q[(state, action)] = ____
alpha = 0.1
gamma = 0.8
Q = np.array([[10,0],[0,20]], dtype='float32')
# Update the Q-table for the ('state1', 'action1') pair
____
print(Q)