實作 Q-learning 更新規則
Q-learning 是強化學習(RL)中的一種 off-policy 演算法,用來在當前狀態下找出最佳動作。與會考量實際採取之下一步動作的 SARSA 不同,Q-learning 在更新 Q 值時,使用未來最大奖勵的最大值,而不考慮實際採取了哪個動作。這個差異讓 Q-learning 即使在探索式,甚至是隨機的政策下,也能學到最適政策。你的任務是實作一個依據 Q-learning 規則來更新 Q 表(Q-table)的函式。下方給出 Q-learning 的更新規則,你需要根據此規則撰寫能更新 Q 表的函式。
NumPy 函式庫已匯入為 np。

本練習屬於課程
使用 Python 的 Gymnasium 進行強化學習
練習說明
- 先擷取給定狀態—動作對的目前 Q 值。
- 在
actions中,找出下一個狀態於所有可能動作下的最大 Q 值。 - 依照 Q-learning 公式更新目前的狀態—動作對之 Q 值。
- 在代理在狀態
0採取動作0、獲得獎勵5、並移動到狀態1的情境下,更新 Q 表Q。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
actions = ['action1', 'action2']
def update_q_table(state, action, reward, next_state):
# Get the old value of the current state-action pair
old_value = ____
# Determine the maximum Q-value for the next state
next_max = ____
# Compute the new value of the current state-action pair
Q[state, action] = ____
alpha = 0.1
gamma = 0.95
Q = np.array([[10, 8], [20, 15]], dtype='float32')
# Update the Q-table
____
print(Q)