记录到 MLflow
在之前的章节中,我们学习了如何设置第一个 MLflow 实验并为其添加自定义标签。我们将很快发现,这些标签对于无缝检索属于更广泛项目的相关实验至关重要。
在上一节中,我们创建了一个数据集,我们将用它来训练一系列模型。
在本节中,我们将深入探讨 MLflow Tracking 的核心功能
- 利用
start_run
上下文创建和高效管理运行。 - 日志记录介绍,涵盖标签、参数和指标。
- 理解模型签名的作用和形成。
- 记录训练好的模型,巩固其在 MLflow 运行中的存在。
但首先,一个基础步骤等待着我们。对于我们即将进行的任务,我们需要一个数据集,专门关注苹果销售。虽然在网上搜索数据集很诱人,但制作我们自己的数据集将确保它完美地符合我们的目标。
制作苹果销售数据集
让我们卷起袖子,构建这个数据集。
我们需要一个数据集来定义受周末、促销和价格波动等各种因素影响的苹果销售动态。该数据集将作为我们预测模型构建和测试的基础。
不过在此之前,让我们回顾一下到目前为止所学到的知识,以及在为本教程目的制作此数据集时如何应用这些原则。
在项目早期开发中使用实验
如下图所示,我尝试了一系列捷径。为了记录我所尝试的内容,我创建了一个新的 MLflow 实验来记录我尝试的状态。由于我使用了不同的数据集和模型,我尝试的每一次后续修改都需要一个新的实验。
找到数据集生成器的可行方法后,结果可以在 MLflow UI 中看到。
一旦我找到了真正有效的方法,我就把所有的东西都清理干净了(删除了它们)。
如果您严格按照本教程进行操作并删除了 Apple_Models
实验,请在继续本教程的下一步之前重新创建它。
使用 MLflow Tracking 跟踪训练
现在我们已经有了数据集,并且已经了解了运行是如何记录的,让我们深入了解如何使用 MLflow 跟踪训练迭代。
首先,我们需要导入所需的模块。
import mlflow
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
请注意,这里我们没有直接导入 MlflowClient
。对于这一部分,我们将使用 fluent
API。fluent API 使用 MLflow 跟踪服务器 URI 的全局引用状态。这个全局实例允许我们使用这些“更高级别”(更简单)的 API 来执行我们可以使用 MlflowClient
完成的所有操作,此外还有一些其他有用的语法(例如我们很快将使用的上下文处理器),以使 MLflow 与 ML 工作负载的集成尽可能简单。
为了使用 fluent
API,我们需要将全局引用设置为跟踪服务器的地址。我们通过以下命令完成此操作
mlflow.set_tracking_uri("http://127.0.0.1:8080")
设置好这些后,我们可以定义更多常量,这些常量将在以运行的形式将训练事件记录到 MLflow 时使用。我们将首先定义一个实验,该实验将用于记录运行。实验与运行的父子关系及其效用将在我们开始迭代一些想法并需要比较测试结果时变得非常清晰。
# Sets the current active experiment to the "Apple_Models" experiment and
# returns the Experiment metadata
apple_experiment = mlflow.set_experiment("Apple_Models")
# Define a run name for this iteration of training.
# If this is not set, a unique name will be auto-generated for your run.
run_name = "apples_rf_test"
# Define an artifact path that the model will be saved to.
artifact_path = "rf_apples"
定义了这些变量后,我们可以开始实际训练模型了。
首先,让我们看看我们将要运行什么。在代码显示之后,我们将查看代码的带注释版本。
# Split the data into features and target and drop irrelevant date field and target field
X = data.drop(columns=["date", "demand"])
y = data["demand"]
# Split the data into training and validation sets
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
params = {
"n_estimators": 100,
"max_depth": 6,
"min_samples_split": 10,
"min_samples_leaf": 4,
"bootstrap": True,
"oob_score": False,
"random_state": 888,
}
# Train the RandomForestRegressor
rf = RandomForestRegressor(**params)
# Fit the model on the training data
rf.fit(X_train, y_train)
# Predict on the validation set
y_pred = rf.predict(X_val)
# Calculate error metrics
mae = mean_absolute_error(y_val, y_pred)
mse = mean_squared_error(y_val, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_val, y_pred)
# Assemble the metrics we're going to write into a collection
metrics = {"mae": mae, "mse": mse, "rmse": rmse, "r2": r2}
# Initiate the MLflow run context
with mlflow.start_run(run_name=run_name) as run:
# Log the parameters used for the model fit
mlflow.log_params(params)
# Log the error metrics that were calculated during validation
mlflow.log_metrics(metrics)
# Log an instance of the trained model for later use
mlflow.sklearn.log_model(sk_model=rf, input_example=X_val, name=artifact_path)
为了帮助可视化 MLflow 跟踪 API 调用如何添加到 ML 训练代码库中,请参见下图。
整合所有内容
让我们看看当我们运行模型训练代码并导航到 MLflow UI 时会是什么样子。
恭喜您完成了 MLflow 跟踪的深入教程!您现在可以返回“入门”内容以了解更多关于 MLflow 的信息。
如果您想尝试一些笔记本以详细了解 MLflow 的工作原理,您可以导航到入门笔记本以在本地下载并运行示例!