演示 Python 中“tf.keras.layers.Dense”的基本实现
Tensorflow 是谷歌提供的机器学习框架。它是一个开源框架,与 Python 结合使用,可以实现算法、深度学习应用程序等等。它用于研究和生产目的。
可以使用以下代码行在 Windows 上安装“tensorflow”包:
pip install tensorflow
张量是 TensorFlow 中使用的数据结构。它有助于连接流图中的边。此流图称为“数据流图”。张量只不过是多维数组或列表。
Keras 是一个用 Python 编写的深度学习 API。它是一个高级 API,具有高效的接口,有助于解决机器学习问题。它运行在 TensorFlow 框架之上。它是为了帮助快速进行实验而构建的。它提供了开发和封装机器学习解决方案所必需的基本抽象和构建块。
Keras 已经存在于 TensorFlow 包中。可以使用以下代码行访问它。
import tensorflow from tensorflow import keras
Keras 函数式 API 有助于创建比使用顺序 API 创建的模型更灵活的模型。函数式 API 可以处理具有非线性拓扑的模型,可以共享层,并可以处理多个输入和输出。深度学习模型通常是一个包含多个层的有向无环图 (DAG)。函数式 API 有助于构建层图。
我们正在使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 有助于通过浏览器运行 Python 代码,无需任何配置,并可免费访问 GPU(图形处理单元)。Colaboratory 是基于 Jupyter Notebook 构建的。以下是代码片段:
示例
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 inputs = keras.Input((4,)) outputs = CustomDense(10)(inputs) print("Keras model is being generated") model = keras.Model(inputs, outputs)
代码来源 - https://tensorflowcn.cn/guide/keras/functional
输出
Keras model is being generated
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
Keras 带有多个内置层,其中一些包括“Conv1D”、“Conv2D”、“Conv2DTranspose”等等。
“call”方法指定由层执行的计算。
“build”方法为层创建权重。
模型已生成。