如何在Python中使用预训练模型同Keras合作?
Tensorflow是由谷歌提供的机器学习框架。它是一个开源框架,与Python一起用于实现算法、深度学习应用等等。它被用于研究和生产目的。
Keras在希腊语中的意思是“角”。Keras是作为项目ONEIROS(开放式智能机器人操作系统)的研究的一部分而开发的。Keras是一个深度学习API,它是用Python编写的。它是一个高级API,具有有助于解决机器学习问题的生产接口。
它运行在Tensorflow框架之上。它被建立来帮助快速进行实验。它提供了必要的抽象和构建块,这些构建块是开发和封装机器学习解决方案必不可少的。
它高度可扩展,并具有跨平台功能。这意味着Keras可以在TPU或GPU集群上运行。Keras模型也可以导出到网络浏览器或手机上运行。
Keras已经包含在Tensorflow包中。可以使用下面的代码行访问它。
import tensorflow
from tensorflow import keras
我们使用Google Colaboratory来运行下面的代码。Google Colab或Colaboratory可在浏览器中运行Python代码,需要零配置,并提供免费访问GPU(图形处理单元)。Colaboratory是建立在Jupyter Notebook之上的。以下是代码片段 −
更多Python相关文章,请阅读:Python 教程
示例
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://www.tensorflow.org/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.h5>83689472/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
解释
-
可以使用顺序模型堆栈以及预训练模型的帮助来初始化分类层。
-
构建完该模型后,它会被编译。
-
一旦编译完成,该模型就可以适用于训练数据。