如何使用 Tensorflow 和预训练模型通过 Python 编译模型?
tensorflowserver side programmingprogramming
可以使用‘compile’方法使用 Tensorflow 和预训练模型编译模型。在此之前,还定义了‘base_learning_rate’。
阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?
包含至少一个层的神经网络称为卷积层。我们可以使用卷积神经网络构建学习模型。
我们将了解如何借助预训练网络的迁移学习对猫和狗的图像进行分类。图像分类迁移学习背后的直觉是,如果在大型通用数据集上训练模型,则该模型可有效地用作视觉世界的通用模型。它会学习特征图,这意味着用户不必从头开始在大型数据集上训练大型模型。
阅读更多: 如何预先训练定制模型?
我们使用 Google Colaboratory 运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,并且不需要任何配置,并且可以免费访问 GPU(图形处理单元)。Colaboratory 是在 Jupyter Notebook 之上构建的。
print("The model is being compiled") base_learning_rate = 0.0001 model.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate), loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy']) print("The base architecture of the model") model.summary()
代码来源 −https://www.tensorflow.org/tutorials/images/transfer_learning
输出
The model is being compiled The base architecture of the model Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_3 (InputLayer) [(None, 160, 160, 3)] 0 _________________________________________________________________ sequential_1 (Sequential) (None, 160, 160, 3) 0 _________________________________________________________________ tf.math.truediv (TFOpLambda) (None, 160, 160, 3) 0 _________________________________________________________________ tf.math.subtract (TFOpLambda (None, 160, 160, 3) 0 _________________________________________________________________ mobilenetv2_1.00_160 (Functi (None, 5, 5, 1280) 2257984 _________________________________________________________________ global_average_pooling2d_2 ( (None, 1280) 0 _________________________________________________________________ dropout (Dropout) (None, 1280) 0 _________________________________________________________________ dense_2 (Dense) (None, 1) 1281 ================================================================= Total params: 2,259,265 Trainable params: 1,281 Non-trainable params: 2,257,984
解释
模型在训练之前进行编译。
由于有两个类,因此使用二元交叉熵损失,from_logits=True,因为模型提供线性输出。
MobileNet 中的 2.5M 个参数被冻结,但它在 Dense 层中包含 1.2K 个可训练参数。
这些层分为两个 tf.Variable 对象,即权重和偏差。