这是HTML5项目的源代码,该项目使用神经网络和遗传算法在Flappy Bird视频游戏中实现机器学习算法。该程序教会了一只小鸟如何最佳地拍打,以便尽可能长时间安全地穿越障碍。
完整的教程提供了更多详细信息和演示,您可以在这里找到:
http://www.askforgametask.com/tutorial/machine-learning-algorithm-flappy-bird
在这里,您还可以观看一个简单的算法介绍的简短视频:
https://www.youtube.com/watch?v=Aewmdojejf0
所有代码均使用用于神经网络实现的Phaser框架和突触神经网络库中的HTML5编写。
要玩游戏,每个单元(鸟)都有自己的神经网络,包括接下来的3层:
一个带有2个神经元的输入层,呈现出鸟看到的内容:
1) horizontal distance between the bird and the closest gap
2) height difference between the bird and the closest gap
带有6个神经元的隐藏层
具有1个神经元的输出层,用于提供以下操作:
if output > 0.5 then flap else do nothing
使用了突触神经网络库来实现整个人工神经网络,而不是从头开始制作新的神经网络。
该程序中实现的机器学习的主要概念是基于神经进化形式。它使用进化算法(例如遗传算法)来训练人工神经网络。这是主要步骤:
与随机神经网络创建新的10个单位(鸟)的新人群
让所有单元通过使用自己的神经网络同时玩游戏
对于每个单元,计算其适应性功能以衡量其质量为:
fitness = total travelled distance - distance to the closest gap
当所有单元被杀死时,使用遗传算法运算符(选择,交叉和突变)评估当前人群,如下所示:
1. sort the units of the current population in decreasing order by their fitness ranking
2. select the top 4 units and mark them as the winners of the current population
3. the 4 winners are directly passed on to the next population
4. to fill the rest of the next population, create 6 offsprings as follows:
- 1 offspring is made by a crossover of two best winners
- 3 offsprings are made by a crossover of two random winners
- 2 offsprings are direct copy of two random winners
5. to add some variations, apply random mutations on each offspring.
回到步骤2
由于该程序是使用移动器框架和突触神经网络库中的HTML5编写的,因此您需要以下文件:
整个游戏逻辑都在gameplay.js文件中实现。它由以下课程组成:
App.Main
,具有以下基本功能的主要例程:
TreeGroup Class
,扩展的移相组类,代表移动障碍。该组包含一个顶部和底部树斑点。
Tree Class
,扩展的移位精灵类,代表树林。
Bird Class
,扩展的移相雪翼级课程代表鸟类精灵。
Text Class
,用于绘制文本的扩展Phaser bitmaptext类。
遗传算法在遗传文件中实现,该文件由以下类组成:
GeneticAlgorithm Class
,即处理所有遗传算法操作的主要类别。它需要两个参数: max_units在人口和top_units中设置总单位数,以设置用于不断发展的人群的许多顶级单位(获胜者)。这是它的基本功能: