如何在Python中使用Keras进行集成?

如何在Python中使用Keras进行集成?

Tensorflow是由Google提供的机器学习框架,它是一个开源框架,与Python一起用于实现算法、深度学习应用等等。它被用于研究和生产目的。

可以使用下面的代码在Windows上安装“tensorflow”包−

pip install tensorflow

Keras是作为ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分开发的。 Keras是一个用Python编写的深度学习API。它是一个高级API,具有可帮助解决机器学习问题的生产界面。它在tensorflow框架之上运行。它专门提供了必要的抽象和构件,这些抽象和构件在开发和封装机器学习解决方案时是必不可少的。

Keras已经存在于Tensorflow包中。可以使用下面的代码访问它。

import tensorflow
from tensorflow import keras

Keras功能API可帮助创建比使用顺序API创建的模型更灵活的模型。功能API可以处理具有非线性拓扑结构的模型,可以共享层,并且可以处理多个输入和输出。深度学习模型通常是包含多个层的有向无环图。功能API有助于构建层的图形。

我们使用Google Colaboratory来运行下面的代码。 Google Colab或Colaboratory可在浏览器上运行Python代码,不需要配置且免费访问GPU(图形处理单元)。 Colaboratory是基于Jupyter笔记本构建的。以下是实现Ensemble模型的代码片段−

更多Python相关文章,请阅读:Python 教程

示例

def get_model():
   inputs = keras.Input(shape=(128,))
   outputs = layers.Dense(1)(inputs)
   return keras.Model(inputs, outputs)
print("Calling the 'get_model' method ")
model_1 = get_model()
model_2 = get_model()
model_3 = get_model()

my_inputs = keras.Input(shape=(128,))
y1 = model_1(my_inputs)
y2 = model_2(my_inputs)
y3 = model_3(my_inputs)
print("The average of the layers in the model")
my_outputs = layers.average([y1, y2, y3])
print("Ensemble model is being created")
ensemble_model = keras.Model(inputs=my_inputs, outputs=my_outputs)

代码来源− https://www.tensorflow.org/guide/keras/functional

输出

Calling the 'get_model' method
The average of the layers in the model
Ensemble model is being created

说明

  • 模型可以嵌套,这意味着它可以包含子模型。

  • 子模型用于集成。

  • 这意味着多个模型组合成一个单一的模型,并将来自每个模型的预测平均。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程