如何使用 Keras 在 Python 中实现迁移学习?


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

张量是 TensorFlow 中使用的数据结构。它有助于连接数据流图中的边。这个数据流图被称为“数据流图”。张量只不过是多维数组或列表。

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

它运行在 TensorFlow 框架之上。它旨在帮助快速进行实验。它提供了开发和封装机器学习解决方案所需的必要抽象和构建块。

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

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

import tensorflow
from tensorflow import keras

我们使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 帮助在浏览器上运行 Python 代码,无需任何配置,并且可以免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。以下是代码片段:

示例

model = keras.Sequential([
   keras.Input(shape=(784))
   layers.Dense(32, activation='relu'),
   layers.Dense(32, activation='relu'),
   layers.Dense(32, activation='relu'),
   layers.Dense(10),
])
print("Load the pre-trained weights")
model.load_weights(...)
print("Freeze all the layers except the last layer")
for layer in model.layers[:-1]:
   layer.trainable = False
print("Recompile the model and train it")
print("The last layer weights will be updated")
model.compile(...)
model.fit(...)

代码来源:https://tensorflowcn.cn/guide/keras/sequential_model

输出

Load the pre-trained weights
Freeze all the layers except the last layer
Recompile the model and train it
The last layer weights will be updated

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 迁移学习是指冻结模型中的底层并训练顶层。

  • 构建顺序模型。

  • 加载预训练的旧模型权重并将其与该模型绑定。

  • 冻结底层,最后一层除外。

  • 迭代各层,并将除最后一层外的每一层的“layer.trainable”设置为“False”。

  • 将其编译并拟合到数据。

更新于:2021年1月18日

273 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告