讨论如何使用 Keras 函数式 API 通过 Python 创建层
Tensorflow 是 Google 提供的机器学习框架。它是一个开源框架,与 Python 结合使用,用于实现算法、深度学习应用程序等。它用于研究和生产目的。它具有优化技术,有助于快速执行复杂的数学运算。
可以使用以下代码行 − 在 Windows 上安装 ‘tensorflow’ 包
pip install tensorflow
Keras 在希腊语中意为 ‘horn’。Keras 是作为 ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分而开发的。Keras 是一个用 Python 编写的深度学习 API。它是一个高级 API,具有高效的接口,有助于解决机器学习问题。它运行在 Tensorflow 框架之上。它旨在帮助快速进行实验。它提供了开发和封装机器学习解决方案所必需的基本抽象和构建块。
Keras 已经存在于 Tensorflow 包中。可以使用下面的代码行访问它。
import tensorflow from tensorflow import keras
与使用顺序 API 创建的模型相比,Keras 函数式 API 有助于创建更灵活的模型。函数式 API 可以与具有非线性拓扑、可以共享层并处理多个输入和输出的模型一起使用。深度学习模型通常是包含多个层的有向无环图 (DAG)。函数式 API 有助于构建层图。
我们正在使用 Google Colaboratory 运行以下代码。 Google Colab 或 Colaboratory 可帮助在浏览器上运行 Python 代码,无需配置,并可免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。以下是代码片段,我们将在其中看到如何使用 Keras 函数式 API 使用 Python 创建层 −
示例
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers inputs = keras.Input(shape=(784,)) print("Demonstration") img_inputs = keras.Input(shape=(32, 32, 3)) print("Dimensions of input") print(inputs.shape) print("The type of input") print(inputs.dtype) print("Layers in the model") dense = layers.Dense(64, activation="relu") x = dense(inputs) x = layers.Dense(64, activation="relu")(x) outputs = layers.Dense(10)(x) print("Model is being built") model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model") print("More information about the model") model.summary()
代码来源 − https://www.tensorflow.org/guide/keras/ functional
输出
解释
创建一个输入节点,并将数据的形状设置为 784 维向量。
返回的输入包含有关‘shape’和‘dtype’的信息先前输入到模型的输入数据。
通过指定输入和输出来创建模型。