
3.7 机器学习深度库Keras
Keras是基于Theano和TensorFlow的深度学习库,以及是一个高层神经网络API。Keras由纯Python编写,使用TensorFlow、Theano以及CNTK作为后端。Keras具有高度模块化、简单性、支持CNN和RNN及可扩充等特性,Keras能够简易和快速地进行原型设计。Keras中文主页:https://keras.io/zh/,如图3-36所示。

图3-36 Keras中文主页
Keras被工业界和学术界广泛采用,与其他任何深度学习框架相比,Keras在行业和研究领域的应用率更高,且Keras API是TensorFlow的官方前端,如图3-37所示。

图3-37 2018年深度学习框架排名
Keras具有如下优点。
(1)Keras已经包含许多经典的学习模型,例如VGG16、VGG19、ResNet50、Inception V3等,位于“keras.applications”的包中,如图3-38所示。

图3-38 Keras的经典学习模型
(2)Keras提供一致而简洁的API,方便用户使用。
(3)Keras提供模块组合使用,例如网络层、损失函数、优化器、初始化策略、激活函数、正则化方法等独立模块,可以使用它们来构建自己的模型。
(4)Keras具有易扩展性。添加新的模块很容易,由于能够轻松地创建可以提高表现力的新模块,Keras更适合高级研究。
(5)与Python融合。Keras没有特定格式的单独配置文件,模型定义在Python代码中,易于调试,且易于扩展。
Keras中提供的学习模型主要有两种:序列(Sequential)和函数式(Functional)模型。
1.序列模型
序列模型是函数式模型的简略版,简顺序结构的单线性模型,是多个网络层的线性堆叠。Keras中有很多层,包括核心层(Core)、卷积层(Convolution)、池化层(Pooling)、全连接层(fully connected layers)等,序列模型可以堆叠这些层。
序列模型的使用说明如下。


2.函数式(Functional)模型
Keras函数式模型是最广泛的一类模型,序列(Sequential)模型只是它的一种特殊情况。函数式模型接口是用户定义多输出模型、非循环有向模型或具有共享层的模型等复杂模型的途径,函数式模型更灵活。
Keras函数式模型的使用方法如下。
(1)建立模型:model=Model(inputs=a, outputs=b)。
(2)载入模型:model=keras . models . load_model( filepath )。
(3)模型编译:model.compile(loss, optimizer)。
(4)模型训练:model.fit(x_train,y_train,epochs,batch_size,verbose=1,validation_data,callbacks=None)。
(5)模型保存:model.save(filepath="*.h5", includeoptimizer=False)。
(6)模型预测:model.predict(data)。
(7)模型评价:model.evaluate(x_test, y_test, batch_size)。
3.7.1 Keras的安装
Keras的pip安装命令为pip install keras,如图3-39所示。

图3-39 Keras的pip安装
Keras在PyCharm中的安装方法是在主界面选择菜单命令“File>Setting”,打开Settings窗口,操作如图3-40所示。

图3-40 Keras在PyCharm中的安装
在深度学习过程中,要想输出Keras神经网络模型的模型图,需要安装Pydot和Graphviz模块。Pydot主页:https://pypi.org/project/pydot/。Graphviz主页:https://graphviz.gitlab.io。Pydot和Graphviz的安装方法如图3-41所示。

图3-41 Pydot和Graphviz安装
3.7.2 Keras的深度学习方式
Keras是一种高级的深度学习API,它的运行需要许多底层库的支持,这些库被用作后端,例如TensorFlow、Theano、CNTK等。Keras的深度学习过程如图3-42所示。
Keras可以使用已经包含的模型进行深度学习,因为Keras已经包含许多经典的学习模型,例如基于ImageNet(ImageNet数据集包含约1500万张图片,22000个类别)训练好的图像模型VGG16、VGG19、ResNet50、Inception V3等,使用这些模型可以简化学习过程。

图3-42 Keras的深度学习过程
下面是使用ResNet50模型进行图像分类的实例,代码如下。

程序运行输出结果如图3-43所示。

图3-43 ResNet50模型图像分类