记录到 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 的工作原理,您可以导航到入门笔记本以在本地下载示例并运行它们!