参考 GitHub 案例,通过 Deep Reinforcement Learning(DQN 算法)训练能玩贪吃蛇的 AI。
环境搭建
基于 python + tensorflow + Keras 搭建训练环境。
- 安装 python 3.6,pip 镜像源设为 https://pypi.tuna.tsinghua.edu.cn/simple
- 从 pip 镜像源手动安装以下依赖:tensorflow 1.13.2、protobuf 3.19.5、h5py 2.10.0、Keras 2.0.0。手动安装的原因是该 GitHub 案例为 2018 年版本,直接安装最新库会产生大量报错。
- 拉取 GitHub 案例 https://github.com/YuriyGuts/snake-ai-reinforcement 到本地。
- 打开案例的 requirements.txt 文件,删除 tensorflow、protobuf、h5py、keras 这几项依赖(第 2 步已手动安装)。
- 切换到案例目录,执行以下命令完成剩余依赖安装:
pip install --upgrade -r requirements.txt
至此环境准备完毕,可以开始训练。
训练
打开 cmd,切换到案例目录,输入以下命令启动训练:
py.exe train.py --level "snakeai/levels/10x10-blank.json" --num-episodes 30000
--num-episodes 30000 表示训练 30000 个样本。训练开始后如下图所示:
默认使用 CPU 计算,i7 9700K 级别训练 30000 场耗时约 8 小时。训练完成后会生成 dqn-final.model 文件,即 DQN 模型,接下来可以用它观看 AI 的游戏效果。
试玩
打开 cmd,切换到案例目录,输入以下命令启动 GUI 对局:
py.exe play.py --interface gui --agent dqn --model "dqn-final.model" --level "snakeai/levels/10x10-blank.json" --num-episodes 10
enjoy yourself~
参考资料
- Introduction to DQN — https://zhuanlan.zhihu.com/p/145102068
- snake-ai-reinforcement — https://github.com/YuriyGuts/snake-ai-reinforcement
- Introduction to Deep Reinforcement Learning — https://zhuanlan.zhihu.com/p/25239682
- Dota 2 with Large Scale Deep Reinforcement Learning
- Mastering Complex Control in MOBA Games with Deep Reinforcement Learning
- https://blog.csdn.net/weixin_45590789/article/details/105666453
- https://cloud.tencent.com/developer/article/1860809
- https://zhuanlan.zhihu.com/p/62225540