Tensorflow 如何使用 Python 返回层实例的构造函数参数?

Tensorflow 是 Google 提供的机器学习框架。它是一个与 Python 结合使用以实现算法、深度学习应用程序等的开源框架。它用于研究和生产目的。

Keras 是作为 ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分而开发的。Keras 是一个深度学习 API,它是用 Python 编写的。它是一种高级 API,具有有助于解决机器学习问题的高效界面。

它运行在 Tensorflow 框架之上。它旨在帮助快速进行实验。它提供了在开发和封装机器学习解决方案中必不可少的基本抽象和构建块。

它具有高度可扩展性,并具有跨平台功能。这意味着 Keras 可以在 TPU 或 GPU 集群上运行。Keras 模型也可以导出以在 Web 浏览器或手机中运行。

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

import tensorflow
from tensorflow import keras

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

我们正在使用 Google Colaboratory 运行以下代码。Google Colab 或 Colaboratory 帮助在浏览器上运行 Python 代码,并且需要零配置和免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。以下是使用 Python 返回层实例的构造函数参数的代码片段 -

示例

class CustomDense(layers.Layer):
   def __init__(self, units=32):
      super(CustomDense, self).__init__()
     self.units= units
   def build(self, input_shape):
     self.w= self.add_weight(
         shape=(input_shape[-1], self.units),
         initializer="random_normal",
         trainable=True,
      )
     self.b= self.add_weight(
         shape=(self.units,), initializer="random_normal", trainable=True
      )
   def call(self, inputs):
      return tf.matmul(inputs, self.w) + self.b
   def get_config(self):
      return {"units": self.units}
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)

model = keras.Model(inputs, outputs)
print("The below function returns constructor arguments for the instance of the layer")
config = model.get_config()

new_model = keras.Model.from_config(config, custom_objects={"CustomDense": CustomDense})

代码信用 - https://www.tensorflow.org/guide/keras/functional

输出结果

The below function returns constructor arguments for the instance of the layer

解释

  • 创建了一个名为“CustomDense”的类,用于向模型添加权重。

  • 另一个名为“get_config”的函数被定义为返回层的每个实例的构造函数参数。

  • 定义模型的输入层。

  • 接下来,定义模型并调用函数。

猜你喜欢