深度強化學習 Ch3.2 : Q-Learning 實作
1. 實作遊戲介紹
這裡利用 GridWorld 的遊戲來測試 Q-learning 的實作,
可以去作者 Github 下載 GridWorld Script
(1).遊戲規則簡介
遊戲是以下'棋盤'上進行,每次 Player 可以走一格,走到終點(+)為獲勝,陷阱(-)則是失敗
遊戲模式 :
- 'static' : 固定棋盤模式,使用預設固定地圖分布
- 'player' : 使用預設地圖,但 Player 位置隨機
- 'random' : 全部布置隨機
Reward 給予規則 :
- 未結束 : reward = -1
- 輸(碰到陷阱) : reward = -10
- 贏(到達終點) : reward = 10
(2).遊戲狀態介紹
遊戲狀態會以一個[3階四維]的陣列(Tensor)儲存,
四維的陣列分別是[玩家位置],[陷阱位置],[終點位置],[牆壁位置]
形成 ( 4 * 4 * 4 ) Shape 的陣列
(3).遊戲操控指令
此遊戲有以下指令可以做操控
2. 訓練 Q-learning
(1). 理論想法
Q-learning 理論公式可以看成以下幾個訓練元素
等於說要建一個 Q 函數的神經網路 model,利用來預測當前狀態各動作的價值,
並利用以上 Update 公式進行 Q model 權重的更新。
(2). 神經網路架構 ( Q 函數架構 )
Q 函數會輸出該狀態各動作的期望價值,所以會有以下 input、output
input : 遊戲當前狀態,為 ( 4 * 4 * 4 ) 矩陣
output : 各動作價值,此遊戲有 4 種動作,輸出四個價值!
神經網路架構:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
其他訓練元素
- Loss function : MSE (Mean Square Error)
- Optimizer(優化器) : Adam
- learning rate : 0.001
- 折扣係數 : 0.9
- 貪婪係數 : 1.0 (最開始設 1 隨機探索)
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
神經網路程式碼
數字轉動作指令
到時候 output 會是各動作的期望價值,如果選擇了其中的動作,
會需要把 index 換成[動作指令],所以利用字典轉換
(3). 訓練架構
可以將訓練架構分為如下,前面 4 步驟(黃色格)就是為了計算 TD-Target,
之後就和 Q-learning Update 步驟相同,
特別說一下這次訓練是訓練 'static' 模式,所以是固定環境位置
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
訓練程式碼
訓練結果

可以看到 Loss 明顯下降
3. 實測模型玩遊戲
定義以下函數來實測訓練的模型,架構與訓練有點像,但只需要 model 預測值
函數會回傳贏 or 輸,Display可以顯示遊戲過程
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
測試函數程式碼
實測模型
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
實測結果

災難性失憶
但如果我們想要訓練 Random 環境 GridWorld 會發現此模型不可用
所以我將訓練步驟的遊戲模式改成 random ,但卻獲得不太好結果…

這是因為模型發生災難性失憶,會在下一篇講解。