常见问题解答
MLflow 3.x 能否加载使用 MLflow 2.x 创建的资源(运行、模型、追踪等)?
是的,MLflow 3.x 可以加载使用 MLflow 2.x 创建的资源,例如运行、模型、追踪等。但是,反之则不成立。
警告
在测试 MLflow 3.x 时,我们强烈建议使用单独的环境,以避免与 MLflow 2.x 发生冲突。
load_model 在加载使用 MLflow 2.x 创建的模型时会抛出 ResourceNotFound 错误。这是什么原因?
例如,以下代码在 MLflow 3.x 中加载模型失败,因为模型伪影未作为运行伪影存储。
import mlflow
with mlflow.start_run() as run:
mlflow.sklearn.log_model(my_model, name="model")
mlflow.sklearn.load_model(mlflow.get_artifact_uri("model"))
# Throws a `ResourceNotFound` error.
为避免此错误,请使用 mlflow.<flavor>.log_model 返回的模型 URI 调用 mlflow.<flavor>.load_model。
import mlflow
with mlflow.start_run() as run:
info = mlflow.sklearn.log_model(my_model, name="model")
# if the result of `log_model` is available (recommended)
mlflow.sklearn.load_model(info.model_uri)
# if only `model_id` is available
mlflow.sklearn.load_model(f"models:/{info.model_id}")
# if neither `model_id` nor `model_uri` is available (deprecated and will be removed in future versions)
mlflow.sklearn.load_model(f"runs:/{run.info.run_id}/model")
为什么会这样?在 MLflow 3.x 中,模型伪影的存储位置与 MLflow 2.x 不同。以下是使用 tree 格式对两个版本进行的比较:
# MLflow 2.x
experiments/
└── <experiment_id>/
└── <run_id>/
└── artifacts/
└── ... # model artifacts are stored here
# MLflow 3.x
experiments/
└── <experiment_id>/
└── models/
└── <model_id>/
└── artifacts/
└── ... # model artifacts are stored here
我想修改我的模型的 requirements.txt 文件。我该如何操作?
您可以使用 mlflow.models.update_model_requirements() 来修改您模型的 requirements.txt 文件,以添加或删除依赖项。以下是如何为模型添加依赖项的示例:
import mlflow
class DummyModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input: list[str]) -> list[str]:
return model_input
model_info = mlflow.pyfunc.log_model(name="model", python_model=DummyModel())
mlflow.models.update_model_requirements(
model_uri=model_info.model_uri,
operation="add",
requirement_list=["scikit-learn"],
)
我还没有准备好升级到 MLflow 3.x。我该如何将 MLflow 版本固定到 2.x?
您可以使用以下命令将 MLflow 固定到最新的 2.x 版本:
pip install 'mlflow<3'