如何使用 Tensorflow 构建自定义层对象?

tensorflowserver side programmingprogramming

Tensorflow 可用于构建自定义层对象,方法是首先创建所需的层,然后在 tf.zeros 方法上使用此层。

阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?

包含至少一个层的神经网络称为卷积层。我们可以使用卷积神经网络来构建学习模型。

图像分类迁移学习背后的直觉是,如果一个模型是在大型通用数据集上训练的,那么这个模型可以有效地用作视觉世界的通用模型。它会学习特征图,这意味着用户不必从头开始在大型数据集上训练大型模型。

TensorFlow Hub 是一个包含预训练 TensorFlow 模型的存储库。 TensorFlow 可用于微调学习模型。我们将了解如何将 TensorFlow Hub 中的模型与 tf.keras 结合使用,使用 TensorFlow Hub 中的图像分类模型。 完成此操作后,可以执行迁移学习以微调自定义图像类别的模型。这是通过使用预训练的分类器模型来获取图像并预测其内容来完成的。这可以在不需要任何训练的情况下完成。 

我们正在使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,并且不需要任何配置,并且可以免费访问 GPU(图形处理单元)。 Colaboratory 是在 Jupyter Notebook 基础上构建的。

示例

import tensorflow as tf
print(tf.test.is_gpu_available())
layer = tf.keras.layers.Dense(100)
print("A dense layer is created")
layer = tf.keras.layers.Dense(10, input_shape=(None, 5))
print("To use the layer, it is called")
layer(tf.zeros([10, 5]))

代码来源 −https://www.tensorflow.org/tutorials/customization/custom_layers

输出

WARNING:tensorflow:From <ipython-input-72-7364732a3855>:2: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
WARNING:tensorflow:From <ipython-input-72-7364732a3855>:2: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
False
A dense layer is created
To use the layer, it is called
<tf.Tensor: shape=(10, 10), dtype=float32, numpy=
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)>

解释

  • tf.keras.layers 包中包含作为对象的层。要构造层,可以构造对象。

  • 许多层将输出维度或通道的数量作为第一个参数。

  • tf.keras 可用作构建神经网络的高级 API。

  • 大多数 TensorFlow API 都可以与 Eager Execution 一起使用。

  • 输入维度的数量不是必需的,但可以从第一次使用该层时推断出来。


相关文章