如何使用 Python 和 Keras 利用预训练模型?
Tensorflow 是 Google 提供的一个机器学习框架。它是一个开源框架,与 Python 结合使用以实现算法、深度学习应用程序等等。它用于研究和生产目的。
Keras 在希腊语中意为“角”。Keras 是作为 ONEIROS 项目(开放式神经电子智能机器人操作系统)研究的一部分开发的。Keras 是一个深度学习 API,用 Python 编写。它是一个高级 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 之上。以下是代码片段:
示例
print("A convolutional model with pre-trained weights is loaded") base_model = keras.applications.Xception( weights='imagenet', include_top=False, pooling='avg') print("This model is freezed") base_model.trainable = False print("A sequential model is used to add a trainable classifier on top of the base") model = keras.Sequential([ base_model, layers.Dense(1000), ]) print("Compile the model") print("Fit the model to the test data") model.compile(...) model.fit(...)
代码来源 - https://tensorflowcn.cn/guide/keras/sequential_model
输出
A convolutional model with pre-trained weights is loaded Downloading data from https://storage.googleapis.com/tensorflow/kerasapplications/xception/xception_weights_tf_dim_ordering_tf_kernels_notop.h583689472/83683744 [==============================] - 1s 0us/step This model is freezed A sequential model is used to add a trainable classifier on top of the base Compile the model Fit the model to the test data
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
可以使用顺序模型堆栈,并借助预训练模型来初始化分类层。
构建此模型后,对其进行编译。
编译完成后,可以将此模型拟合到训练数据。