Keras¶
关于此页面
这是 BentoML 中 Keras 的 API 参考。有关如何在 BentoML 中使用 Keras 的更多信息,请参阅 Keras 指南。
- bentoml.keras.save_model(name: Tag | str, model: tf_ext.KerasModel, *, tf_signatures: 'tf_ext.ConcreteFunction' | None = None, tf_save_options: 'tf_ext.SaveOptions' | None = None, include_optimizer: bool = False, signatures: t.Dict[str, ModelSignature] | t.Dict[str,ModelSignatureDict] | None = None, labels: t.Optional[t.Dict[str, str]] = None, custom_objects: t.Optional[t.Dict[str, t.Any]] = None, external_modules: t.Optional[t.List[ModuleType]] = None, metadata: t.Optional[t.Dict[str, t.Any]] = None) bentoml.Model ¶
将模型实例保存到 BentoML 模型仓库。
- 参数:
name – 给定模型实例的名称。该名称应通过 Python 标识符检查。
model – 要保存到 BentoML 模型仓库的 Keras 模型实例。
tf_signatures – 有关更多信息,请参阅 Tensorflow 文档中的 Signatures 解释。
tf_save_options –
tf.saved_model.SaveOptions
对象,指定保存选项。signatures – 暴露用于在目标模型上运行推理的方法。在使用 bentoml.Service 提供模型服务时,signatures 用于创建 Runner 实例。
labels – 用户定义的用于管理模型的标签,例如 team=nlp, stage=dev
custom_objects – Keras 自定义对象的字典(如果指定)。
external_modules – 用户定义的要与模型或自定义对象一起保存的额外 Python 模块,例如分词器模块、预处理器模块、模型配置模块
metadata – 给定模型的自定义元数据。
- 返回:
包含已保存 Keras 模型实例的 BentoML 模型。
- 返回类型:
Model
示例
import bentoml import tensorflow as tf import tensorflow.keras as keras def custom_activation(x): return tf.nn.tanh(x) ** 2 class CustomLayer(keras.layers.Layer): def __init__(self, units=32, **kwargs): super(CustomLayer, self).__init__(**kwargs) self.units = tf.Variable(units, name="units") def call(self, inputs, training=False): if training: return inputs * self.units else: return inputs def get_config(self): config = super(CustomLayer, self).get_config() config.update({"units": self.units.numpy()}) return config def KerasSequentialModel() -> keras.models.Model: net = keras.models.Sequential( ( keras.layers.Dense( units=1, input_shape=(5,), use_bias=False, kernel_initializer=keras.initializers.Ones(), ), ) ) opt = keras.optimizers.Adam(0.002, 0.5) net.compile(optimizer=opt, loss="binary_crossentropy", metrics=["accuracy"]) return net model = KerasSequentialModel() # `save` a given model and retrieve coresponding tag: bento_model = bentoml.keras.save_model("keras_model", model) # `save` a given model with custom objects definition: custom_objects = { "CustomLayer": CustomLayer, "custom_activation": custom_activation, }, custom_bento_model = bentoml.keras.save_model("custom_obj_keras", custom_objects=custom_objects)
- bentoml.keras.load_model(bento_model: str | Tag | bentoml.Model, device_name: str = '/device:CPU:0') tf_ext.KerasModel ¶
从 BentoML 本地模型仓库加载给定名称的模型。
- 参数:
bento_model (
str
|
Tag
|
Model
) – 要从仓库获取的模型标签,或要从中加载模型的 BentoML ~bentoml.Model 实例。device_name (
str
|None
) – 加载模型的设备 ID。设备 ID 格式应与 tf.device 兼容
- 返回:
从 BentoML 模型仓库加载的用户
keras.Model
实例。- 返回类型:
keras.Model
示例
import bentoml # load a model back into memory: loaded = bentoml.keras.load_model("keras_model")