mlflow.tensorflow
The mlflow.tensorflow module provides an API for logging and loading TensorFlow models. This module exports TensorFlow models with the following flavors
- TensorFlow (native) format
This is the main flavor that can be loaded back into TensorFlow.
mlflow.pyfuncProduced for use by generic pyfunc-based deployment tools and batch inference.
- mlflow.tensorflow.autolog(log_models=True, log_datasets=True, disable=False, exclusive=False, disable_for_unsupported_versions=False, silent=False, registered_model_name=None, log_input_examples=False, log_model_signatures=True, saved_model_kwargs=None, keras_model_kwargs=None, extra_tags=None, log_every_epoch=True, log_every_n_steps=None, checkpoint=True, checkpoint_monitor='val_loss', checkpoint_mode='min', checkpoint_save_best_only=True, checkpoint_save_weights_only=False, checkpoint_save_freq='epoch')[source]
注意
Autologging is known to be compatible with the following package versions:
2.16.0<=tensorflow<=2.20.0. Autologging may not succeed when used with package versions outside of this range.Enables autologging for
tf.keras. Note that onlytensorflow>=2.3are supported. As an example, try running the Keras/TensorFlow example.For each TensorFlow module, autologging captures the following information
- tf.keras
Metrics and Parameters
Training and validation loss.
User-specified metrics.
Optimizer config, e.g., learning_rate, momentum, etc.
Training configs, e.g., epochs, batch_size, etc.
工件
Model summary on training start.
Saved Keras model in MLflow Model format.
TensorBoard logs on training end.
- tf.keras.callbacks.EarlyStopping
Metrics and Parameters
Metrics from the
EarlyStoppingcallbacks:stopped_epoch,restored_epoch,restore_best_weight, etcfit()orfit_generator()parameters associated withEarlyStopping:min_delta,patience,baseline,restore_best_weights, etc
Refer to the autologging tracking documentation for more information on TensorFlow workflows.
Note that autologging cannot be used together with explicit MLflow callback, i.e., mlflow.tensorflow.MlflowCallback, because it will cause the same metrics to be logged twice. If you want to include mlflow.tensorflow.MlflowCallback in the callback list, please turn off autologging by calling mlflow.tensorflow.autolog(disable=True).
- 参数
log_models – If
True, trained models are logged as MLflow model artifacts. IfFalse, trained models are not logged.log_datasets – 如果为
True,则数据集信息将被记录到 MLflow Tracking。如果为False,则不记录数据集信息。disable – If
True, disables the TensorFlow autologging integration. IfFalse, enables the TensorFlow integration autologging integration.exclusive – 如果为
True,则自动记录的内容不会记录到用户创建的流畅运行中。如果为False,则自动记录的内容将记录到活动的流畅运行中,该运行可能是用户创建的。disable_for_unsupported_versions – If
True, disable autologging for versions of tensorflow that have not been tested against this version of the MLflow client or are incompatible.silent – If
True, suppress all event logs and warnings from MLflow during TensorFlow autologging. IfFalse, show all events and warnings during TensorFlow autologging.registered_model_name – If given, each time a model is trained, it is registered as a new model version of the registered model with this name. The registered model is created if it does not already exist.
log_input_examples – If
True, input examples from training datasets are collected and logged along with tf/keras model artifacts during training. IfFalse, input examples are not logged.log_model_signatures – If
True,ModelSignaturesdescribing model inputs and outputs are collected and logged along with tf/keras model artifacts during training. IfFalse, signatures are not logged. Note that logging TensorFlow models with signatures changes their pyfunc inference behavior when Pandas DataFrames are passed topredict(). When a signature is present, annp.ndarray(for single-output models) or a mapping fromstr->np.ndarray(for multi-output models) is returned; when a signature is not present, a Pandas DataFrame is returned.saved_model_kwargs – a dict of kwargs to pass to
tensorflow.saved_model.savemethod.keras_model_kwargs – a dict of kwargs to pass to
keras_model.savemethod.extra_tags – 要为自动日志记录创建的每个托管运行设置的额外标签的字典。
log_every_epoch – If True, training metrics will be logged at the end of each epoch.
log_every_n_steps – If set, training metrics will be logged every n training steps. log_every_n_steps must be None when log_every_epoch=True.
checkpoint – Enable automatic model checkpointing.
checkpoint_monitor – In automatic model checkpointing, the metric name to monitor if you set model_checkpoint_save_best_only to True.
checkpoint_mode – one of {“min”, “max”}. In automatic model checkpointing, if save_best_only=True, the decision to overwrite the current save file is made based on either the maximization or the minimization of the monitored quantity.
checkpoint_save_best_only – If True, automatic model checkpointing only saves when the model is considered the “best” model according to the quantity monitored and previous checkpoint model is overwritten.
checkpoint_save_weights_only – In automatic model checkpointing, if True, then only the model’s weights will be saved. Otherwise, the optimizer states, lr-scheduler states, etc are added in the checkpoint too.
checkpoint_save_freq – “epoch” or integer. When using “epoch”, the callback saves the model after each epoch. When using integer, the callback saves the model at end of this many batches. Note that if the saving isn’t aligned to epochs, the monitored metric may potentially be less reliable (it could reflect as little as 1 batch, since the metrics get reset every epoch). Defaults to “epoch”.
- mlflow.tensorflow.get_default_conda_env()[source]
- 返回
The default Conda environment for MLflow Models produced by calls to
save_model()andlog_model().
- mlflow.tensorflow.get_default_pip_requirements(include_cloudpickle=False)[source]
- 返回
A list of default pip requirements for MLflow Models produced by this flavor. Calls to
save_model()andlog_model()produce a pip environment that, at minimum, contains these requirements.
- mlflow.tensorflow.get_global_custom_objects()[source]
- 返回
A live reference to the global dictionary of custom objects.
- mlflow.tensorflow.load_checkpoint(model=None, run_id=None, epoch=None, global_step=None)[source]
If you enable “checkpoint” in autologging, during Keras model training execution, checkpointed models are logged as MLflow artifacts. Using this API, you can load the checkpointed model.
If you want to load the latest checkpoint, set both epoch and global_step to None. If “checkpoint_save_freq” is set to “epoch” in autologging, you can set epoch param to the epoch of the checkpoint to load specific epoch checkpoint. If “checkpoint_save_freq” is set to an integer in autologging, you can set global_step param to the global step of the checkpoint to load specific global step checkpoint. epoch param and global_step can’t be set together.
- 参数
model – A Keras model, this argument is required only when the saved checkpoint is “weight-only”.
run_id – The id of the run which model is logged to. If not provided, current active run is used.
epoch – The epoch of the checkpoint to be loaded, if you set “checkpoint_save_freq” to “epoch”.
global_step – The global step of the checkpoint to be loaded, if you set “checkpoint_save_freq” to an integer.
- 返回
The instance of a Keras model restored from the specified checkpoint.
import mlflow mlflow.tensorflow.autolog(checkpoint=True, checkpoint_save_best_only=False) model = create_tf_keras_model() # Create a Keras model with mlflow.start_run() as run: model.fit(data, label, epoch=10) run_id = run.info.run_id # load latest checkpoint model latest_checkpoint_model = mlflow.tensorflow.load_checkpoint(run_id=run_id) # load history checkpoint model logged in second epoch checkpoint_model = mlflow.tensorflow.load_checkpoint(run_id=run_id, epoch=2)
- mlflow.tensorflow.load_model(model_uri, dst_path=None, saved_model_kwargs=None, keras_model_kwargs=None)[source]
Load an MLflow model that contains the TensorFlow flavor from the specified path.
- 参数
model_uri –
MLflow 模型在 URI 格式中的位置。例如:
/Users/me/path/to/local/modelrelative/path/to/local/models3://my_bucket/path/to/modelruns:/<mlflow_run_id>/run-relative/path/to/modelmodels:/<model_name>/<model_version>models:/<model_name>/<stage>
For more information about supported URI schemes, see Referencing Artifacts.
dst_path – The local filesystem path to which to download the model artifact. This directory must already exist. If unspecified, a local output path will be created.
saved_model_kwargs – kwargs to pass to
tensorflow.saved_model.loadmethod. Only available when you are loading a tensorflow2 core model.keras_model_kwargs – kwargs to pass to
keras.models.load_modelmethod. Only available when you are loading a Keras model.
- 返回
A callable graph (tf.function) that takes inputs and returns inferences.
- mlflow.tensorflow.log_model(model, artifact_path: str | None = None, custom_objects=None, conda_env=None, code_paths=None, signature: mlflow.models.signature.ModelSignature = None, input_example: Union[pandas.core.frame.DataFrame, numpy.ndarray, dict, list, csr_matrix, csc_matrix, str, bytes, tuple] = None, registered_model_name=None, await_registration_for=300, pip_requirements=None, extra_pip_requirements=None, saved_model_kwargs=None, keras_model_kwargs=None, metadata=None, name: str | None = None, params: dict[str, typing.Any] | None = None, tags: dict[str, typing.Any] | None = None, model_type: str | None = None, step: int = 0, model_id: str | None = None)[source]
Log a TF2 core model (inheriting tf.Module) or a Keras model in MLflow Model format.
注意
If you log a Keras or TensorFlow model without a signature, inference with
mlflow.pyfunc.spark_udf()will not work unless the model’s pyfunc representation accepts pandas DataFrames as inference inputs.You can infer a model’s signature by calling the
mlflow.models.infer_signature()API on features from the model’s test dataset. You can also manually create a model signature, for examplefrom mlflow.types.schema import Schema, TensorSpec from mlflow.models import ModelSignature import numpy as np input_schema = Schema( [ TensorSpec(np.dtype(np.uint64), (-1, 5), "field1"), TensorSpec(np.dtype(np.float32), (-1, 3, 2), "field2"), ] ) # Create the signature for a model that requires 2 inputs: # - Input with name "field1", shape (-1, 5), type "np.uint64" # - Input with name "field2", shape (-1, 3, 2), type "np.float32" signature = ModelSignature(inputs=input_schema)
- 参数
model – The TF2 core model (inheriting tf.Module) or Keras model to be saved.
artifact_path – Deprecated. Use name instead.
custom_objects – A Keras
custom_objectsdictionary mapping names (strings) to custom classes or functions associated with the Keras model. MLflow saves these custom layers using CloudPickle and restores them automatically when the model is loaded withmlflow.tensorflow.load_model()andmlflow.pyfunc.load_model().conda_env –
Either a dictionary representation of a Conda environment or the path to a conda environment yaml file. If provided, this describes the environment this model should be run in. At a minimum, it should specify the dependencies contained in get_default_conda_env(). If
None, a conda environment with pip requirements inferred bymlflow.models.infer_pip_requirements()is added to the model. If the requirement inference fails, it falls back to using get_default_pip_requirements. pip requirements fromconda_envare written to a piprequirements.txtfile and the full conda environment is written toconda.yaml. The following is an example dictionary representation of a conda environment{ "name": "mlflow-env", "channels": ["conda-forge"], "dependencies": [ "python=3.8.15", { "pip": [ "tensorflow==x.y.z" ], }, ], }
code_paths –
A list of local filesystem paths to Python file dependencies (or directories containing file dependencies). These files are prepended to the system path when the model is loaded. Files declared as dependencies for a given model should have relative imports declared from a common root path if multiple files are defined with import dependencies between them to avoid import errors when loading the model.
For a detailed explanation of
code_pathsfunctionality, recommended usage patterns and limitations, see the code_paths usage guide.signature –
an instance of the
ModelSignatureclass that describes the model’s inputs and outputs. If not specified but aninput_exampleis supplied, a signature will be automatically inferred based on the supplied input example and model. To disable automatic signature inference when providing an input example, setsignaturetoFalse. To manually infer a model signature, callinfer_signature()on datasets with valid model inputs, such as a training dataset with the target column omitted, and valid model outputs, like model predictions made on the training dataset, for examplefrom mlflow.models import infer_signature train = df.drop_column("target_label") predictions = ... # compute model predictions signature = infer_signature(train, predictions)
input_example – 一个或多个有效的模型输入实例。输入示例用作要馈送给模型的数据的提示。它将被转换为 Pandas DataFrame,然后使用 Pandas 的面向拆分(split-oriented)格式序列化为 json,或者转换为 numpy 数组,其中示例将通过转换为列表来序列化为 json。字节将进行 base64 编码。当
signature参数为None时,输入示例用于推断模型签名。registered_model_name – 如果提供,则在
registered_model_name下创建一个模型版本,如果给定名称的注册模型不存在,也会创建该注册模型。await_registration_for – 等待模型版本完成创建并处于
READY状态的秒数。默认情况下,函数等待五分钟。指定 0 或 None 可跳过等待。pip_requirements – Either an iterable of pip requirement strings (e.g.
["tensorflow", "-r requirements.txt", "-c constraints.txt"]) or the string path to a pip requirements file on the local filesystem (e.g."requirements.txt"). If provided, this describes the environment this model should be run in. IfNone, a default list of requirements is inferred bymlflow.models.infer_pip_requirements()from the current software environment. If the requirement inference fails, it falls back to using get_default_pip_requirements. Both requirements and constraints are automatically parsed and written torequirements.txtandconstraints.txtfiles, respectively, and stored as part of the model. Requirements are also written to thepipsection of the model’s conda environment (conda.yaml) file.extra_pip_requirements –
Either an iterable of pip requirement strings (e.g.
["pandas", "-r requirements.txt", "-c constraints.txt"]) or the string path to a pip requirements file on the local filesystem (e.g."requirements.txt"). If provided, this describes additional pip requirements that are appended to a default set of pip requirements generated automatically based on the user’s current software environment. Both requirements and constraints are automatically parsed and written torequirements.txtandconstraints.txtfiles, respectively, and stored as part of the model. Requirements are also written to thepipsection of the model’s conda environment (conda.yaml) file.警告
以下参数不能同时指定
conda_envpip_requirementsextra_pip_requirements
此示例演示了如何使用
pip_requirements和extra_pip_requirements指定 pip requirements。saved_model_kwargs – a dict of kwargs to pass to
tensorflow.saved_model.savemethod.keras_model_kwargs – a dict of kwargs to pass to
keras_model.savemethod.metadata – 传递给模型并存储在 MLmodel 文件中的自定义元数据字典。
name – 模型名称。
params – 要与模型一起记录的参数字典。
tags – 要与模型一起记录的标签字典。
model_type – 模型的类型。
step – 记录模型输出和指标的步骤
model_id – 模型的 ID。
- 返回
一个
ModelInfo实例,其中包含已记录模型的元数据。
- mlflow.tensorflow.save_model(model, path, conda_env=None, code_paths=None, mlflow_model=None, custom_objects=None, signature: mlflow.models.signature.ModelSignature = None, input_example: Union[pandas.core.frame.DataFrame, numpy.ndarray, dict, list, csr_matrix, csc_matrix, str, bytes, tuple] = None, pip_requirements=None, extra_pip_requirements=None, saved_model_kwargs=None, keras_model_kwargs=None, metadata=None)[source]
Save a TF2 core model (inheriting tf.Module) or Keras model in MLflow Model format to a path on the local file system.
注意
If you save a Keras or TensorFlow model without a signature, inference with
mlflow.pyfunc.spark_udf()will not work unless the model’s pyfunc representation accepts pandas DataFrames as inference inputs. You can infer a model’s signature by calling themlflow.models.infer_signature()API on features from the model’s test dataset. You can also manually create a model signature, for examplefrom mlflow.types.schema import Schema, TensorSpec from mlflow.models import ModelSignature import numpy as np input_schema = Schema( [ TensorSpec(np.dtype(np.uint64), (-1, 5), "field1"), TensorSpec(np.dtype(np.float32), (-1, 3, 2), "field2"), ] ) # Create the signature for a model that requires 2 inputs: # - Input with name "field1", shape (-1, 5), type "np.uint64" # - Input with name "field2", shape (-1, 3, 2), type "np.float32" signature = ModelSignature(inputs=input_schema)
- 参数
model – The Keras model or Tensorflow module to be saved.
path – Local path where the MLflow model is to be saved.
conda_env –
Either a dictionary representation of a Conda environment or the path to a conda environment yaml file. If provided, this describes the environment this model should be run in. At a minimum, it should specify the dependencies contained in get_default_conda_env(). If
None, a conda environment with pip requirements inferred bymlflow.models.infer_pip_requirements()is added to the model. If the requirement inference fails, it falls back to using get_default_pip_requirements. pip requirements fromconda_envare written to a piprequirements.txtfile and the full conda environment is written toconda.yaml. The following is an example dictionary representation of a conda environment{ "name": "mlflow-env", "channels": ["conda-forge"], "dependencies": [ "python=3.8.15", { "pip": [ "tensorflow==x.y.z" ], }, ], }
code_paths –
A list of local filesystem paths to Python file dependencies (or directories containing file dependencies). These files are prepended to the system path when the model is loaded. Files declared as dependencies for a given model should have relative imports declared from a common root path if multiple files are defined with import dependencies between them to avoid import errors when loading the model.
For a detailed explanation of
code_pathsfunctionality, recommended usage patterns and limitations, see the code_paths usage guide.mlflow_model – MLflow model configuration to which to add the
tensorflowflavor.custom_objects – A Keras
custom_objectsdictionary mapping names (strings) to custom classes or functions associated with the Keras model. MLflow saves these custom layers using CloudPickle and restores them automatically when the model is loaded withmlflow.tensorflow.load_model()andmlflow.pyfunc.load_model().signature –
an instance of the
ModelSignatureclass that describes the model’s inputs and outputs. If not specified but aninput_exampleis supplied, a signature will be automatically inferred based on the supplied input example and model. To disable automatic signature inference when providing an input example, setsignaturetoFalse. To manually infer a model signature, callinfer_signature()on datasets with valid model inputs, such as a training dataset with the target column omitted, and valid model outputs, like model predictions made on the training dataset, for examplefrom mlflow.models import infer_signature train = df.drop_column("target_label") predictions = ... # compute model predictions signature = infer_signature(train, predictions)
input_example – 一个或多个有效的模型输入实例。输入示例用作要馈送给模型的数据的提示。它将被转换为 Pandas DataFrame,然后使用 Pandas 的面向拆分(split-oriented)格式序列化为 json,或者转换为 numpy 数组,其中示例将通过转换为列表来序列化为 json。字节将进行 base64 编码。当
signature参数为None时,输入示例用于推断模型签名。pip_requirements – Either an iterable of pip requirement strings (e.g.
["tensorflow", "-r requirements.txt", "-c constraints.txt"]) or the string path to a pip requirements file on the local filesystem (e.g."requirements.txt"). If provided, this describes the environment this model should be run in. IfNone, a default list of requirements is inferred bymlflow.models.infer_pip_requirements()from the current software environment. If the requirement inference fails, it falls back to using get_default_pip_requirements. Both requirements and constraints are automatically parsed and written torequirements.txtandconstraints.txtfiles, respectively, and stored as part of the model. Requirements are also written to thepipsection of the model’s conda environment (conda.yaml) file.extra_pip_requirements –
Either an iterable of pip requirement strings (e.g.
["pandas", "-r requirements.txt", "-c constraints.txt"]) or the string path to a pip requirements file on the local filesystem (e.g."requirements.txt"). If provided, this describes additional pip requirements that are appended to a default set of pip requirements generated automatically based on the user’s current software environment. Both requirements and constraints are automatically parsed and written torequirements.txtandconstraints.txtfiles, respectively, and stored as part of the model. Requirements are also written to thepipsection of the model’s conda environment (conda.yaml) file.警告
以下参数不能同时指定
conda_envpip_requirementsextra_pip_requirements
此示例演示了如何使用
pip_requirements和extra_pip_requirements指定 pip requirements。saved_model_kwargs – a dict of kwargs to pass to
tensorflow.saved_model.savemethod if the model to be saved is a Tensorflow module.keras_model_kwargs – a dict of kwargs to pass to
model.savemethod if the model to be saved is a keras model.metadata – 传递给模型并存储在 MLmodel 文件中的自定义元数据字典。
- class mlflow.tensorflow.MlflowCallback(log_every_epoch=True, log_every_n_steps=None)[source]
Callback for logging Tensorflow training metrics to MLflow.
此回调函数在训练开始时记录模型信息,并根据用户定义(每 epoch 或每 n 步)将训练指标记录到 MLflow。
- 参数
log_every_epoch – bool, 如果为 True,则每 epoch 记录一次指标。如果为 False,则每 n 步记录一次指标。
log_every_n_steps – int, 每 n 步记录一次指标。如果为 None,则每 epoch 记录一次指标。如果 log_every_epoch=True,则此参数必须为 None。
from tensorflow import keras import mlflow import numpy as np # Prepare data for a 2-class classification. data = tf.random.uniform([8, 28, 28, 3]) label = tf.convert_to_tensor(np.random.randint(2, size=8)) model = keras.Sequential( [ keras.Input([28, 28, 3]), keras.layers.Flatten(), keras.layers.Dense(2), ] ) model.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(0.001), metrics=[keras.metrics.SparseCategoricalAccuracy()], ) with mlflow.start_run() as run: model.fit( data, label, batch_size=4, epochs=2, callbacks=[mlflow.keras.MlflowCallback(run)], )
- on_batch_end(batch, logs=None)[源]
以用户指定的频率在每个 batch 结束时记录指标。
- on_epoch_end(epoch, logs=None)[源]
在每个 epoch 结束时记录指标。
- on_test_end(logs=None)[源]
在验证结束时记录验证指标。
- on_train_begin(logs=None)[源]
在训练开始时记录模型架构和优化器配置。