如何使用 Python 在 Tensorflow 中组合层?
Tensorflow 可以通过定义一个继承自 'ResnetIdentityBlock' 的类来组合层。这用于定义一个块,该块可用于组合层。
阅读更多: 什么是 TensorFlow 以及 Keras 如何与 TensorFlow 协同工作以创建神经网络?
包含至少一层的神经网络称为卷积层。我们可以使用卷积神经网络构建学习模型。
TensorFlow Hub 是一个包含预训练 TensorFlow 模型的存储库。 TensorFlow 可用于微调学习模型。 我们将了解如何使用 TensorFlow Hub 中的模型与 tf.keras,使用 TensorFlow Hub 中的图像分类模型。完成此操作后,可以执行迁移学习以针对自定义图像类别微调模型。这是通过使用预训练的分类器模型来获取图像并预测它是做什么的来完成的。这可以在不需要任何训练的情况下完成。
我们正在使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 帮助通过浏览器运行 Python 代码,并且无需任何配置即可免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。
示例
print("Composing layers")
class ResnetIdentityBlock(tf.keras.Model):
def __init__(self, kernel_size, filters):
super(ResnetIdentityBlock, self).__init__(name='')
filters1, filters2, filters3 = filters
self.conv2a = tf.keras.layers.Conv2D(filters1, (1, 1))
self.bn2a = tf.keras.layers.BatchNormalization()
self.conv2b = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same')
self.bn2b = tf.keras.layers.BatchNormalization()
self.conv2c = tf.keras.layers.Conv2D(filters3, (1, 1))
self.bn2c = tf.keras.layers.BatchNormalization()
def call(self, input_tensor, training=False):
x = self.conv2a(input_tensor)
x = self.bn2a(x, training=training)
x = tf.nn.relu(x)
x = self.conv2b(x)
x = self.bn2b(x, training=training)
x = tf.nn.relu(x)
x = self.conv2c(x)
x = self.bn2c(x, training=training)
x += input_tensor
return tf.nn.relu(x)
print("The layer is called")
block = ResnetIdentityBlock(1, [1, 2, 3])
_ = block(tf.zeros([1, 2, 3, 3]))
block.layers
len(block.variables)
block.summary()代码来源 - https://tensorflowcn.cn/tutorials/customization/custom_layers
输出
Composing layers The layer is called Model: "resnet_identity_block" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) multiple 4 _________________________________________________________________ batch_normalization (BatchNo multiple 4 _________________________________________________________________ conv2d_1 (Conv2D) multiple 4 _________________________________________________________________ batch_normalization_1 (Batch multiple 8 _________________________________________________________________ conv2d_2 (Conv2D) multiple 9 _________________________________________________________________ batch_normalization_2 (Batch multiple 12 ================================================================= Total params: 41 Trainable params: 29 Non-trainable params: 12
解释
resnet 中的每个残差块都由卷积、批处理归一化和快捷方式组成。
层也可以嵌套在其他层中。
当我们需要模型方法(例如 Model.fit、Model.evaluate 和 Model.save)时,可以从 keras.Model 继承。
keras.Model 用于代替 keras.layers.Layer,这有助于跟踪变量。
keras.Model 会跟踪其内部层,从而更容易检查这些层。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP