MLflow 是一个用于管理机器学习生命周期的开源平台,包括实验跟踪、项目管理和模型部署等功能。其中,MLflow 的超参数调优(Hyperparameter Tuning)功能可以帮助你自动化地搜索最优的超参数组合。以下是使用 MLflow 进行超参数调优实验的基本步骤:
首先,确保你已经安装了 MLflow。你可以使用 pip 来安装:
pip install mlflow在开始实验之前,你需要启动 MLflow 跟踪服务器。你可以在本地启动一个跟踪服务器,或者使用远程服务器。
mlflow server --backend-store-uri sqlite:///mlruns --default-artifact-root ./artifacts编写一个训练脚本,该脚本应该能够接受超参数作为命令行参数,并使用这些参数训练模型。以下是一个简单的示例:
import mlflow
import mlflow.sklearn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import argparse
def train_model(hyperparams):
# 加载数据
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
# 创建模型
model = RandomForestClassifier(**hyperparams)
# 训练模型
with mlflow.start_run():
mlflow.log_params(hyperparams)
model.fit(X_train, y_train)
# 评估模型
accuracy = model.score(X_test, y_test)
mlflow.log_metric("accuracy", accuracy)
# 保存模型
mlflow.sklearn.log_model(model, "model")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--n_estimators", type=int, default=100)
parser.add_argument("--max_depth", type=int, default=None)
args = parser.parse_args()
hyperparams = {
"n_estimators": args.n_estimators,
"max_depth": args.max_depth
}
train_model(hyperparams)你可以使用 MLflow 的 tuner 模块来进行超参数搜索。以下是一个使用 tuner 模块的示例:
import mlflow
from mlflow.tracking import MlflowClient
from mlflow.tuning import HyperparameterTuner, ParamGridBuilder
# 定义超参数搜索空间
param_grid = ParamGridBuilder() \
.add_grid("n_estimators", [50, 100, 200]) \
.add_grid("max_depth", [None, 10, 20, 30]) \
.build()
# 创建超参数调优器
tuner = HyperparameterTuner(
target_metric_name="accuracy",
objective_metric_name="accuracy",
param_grid=param_grid,
algorithm="random",
num_trials=5
)
# 启动超参数搜索
tuner.fit(
params={},
experiment_name="hyperparameter-tuning-experiment",
run_name="run-1"
)
# 获取最佳运行
best_run = tuner.get_best_run()
print(f"Best run: {best_run.info.run_uuid}")
print(f"Best params: {best_run.data.params}")
print(f"Best accuracy: {best_run.data.metrics['accuracy']}")你可以通过 MLflow UI 查看实验结果。启动 MLflow UI:
mlflow ui然后在浏览器中打开 http://127.0.0.1:5000,你将看到实验的详细信息,包括每次运行的参数、指标和模型文件。
通过以上步骤,你可以使用 MLflow 进行超参数调优实验,并找到最优的超参数组合。