Tas*_*sos 5 python scikit-learn mlflow
我刚刚开始使用 MLFlow,我对它的功能感到满意。但是,我找不到在GridSearchCVscikit learn 中记录不同运行的方法。
例如,我可以手动执行此操作
params = ['l1', 'l2']
for param in params:
with mlflow.start_run(experiment_id=1):
clf = LogisticRegression(penalty = param).fit(X_train, y_train)
y_predictions = clf.predict(X_test)
precision = precision_score(y_test, y_predictions)
recall = recall_score(y_test, y_predictions)
f1 = f1_score(y_test, y_predictions)
mlflow.log_param("penalty", param)
mlflow.log_metric("Precision", precision)
mlflow.log_metric("Recall", recall)
mlflow.log_metric("F1", f1)
mlflow.sklearn.log_model(clf, "model")
Run Code Online (Sandbox Code Playgroud)
但是当我想使用GridSearchCV类似的
pipe = Pipeline([('classifier' , RandomForestClassifier())])
param_grid = [
{'classifier' : [LogisticRegression()],
'classifier__penalty' : ['l1', 'l2'],
'classifier__C' : np.logspace(-4, 4, 20),
'classifier__solver' : ['liblinear']},
{'classifier' : [RandomForestClassifier()],
'classifier__n_estimators' : list(range(10,101,10)),
'classifier__max_features' : list(range(6,32,5))}
]
clf = GridSearchCV(pipe, param_grid = param_grid, cv = 5, verbose=True, n_jobs=-1)
best_clf = clf.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud)
我想不出任何方法来记录 GridSearch 测试的所有单个模型。有没有办法做到这一点,或者我必须继续使用手动过程?
我推荐hyperopt而不是 scikit-learn 的GridSearchCV. Hyperopt 可以使用贝叶斯优化来搜索空间hyperopt.tpe.suggest。它比网格搜索更快地获得良好的参数,并且无论空间大小如何,您都可以限制迭代次数,因此对于大空间来说它肯定更好。由于您对各个运行中的工件感兴趣,因此您可能更喜欢 hyperopt 的随机搜索,它仍然具有能够选择执行多少次运行的优点。
您可以使用 Spark 非常轻松地并行化搜索hyperopt.SparkTrials(这里有一个更完整的示例)。请注意,您可以继续使用 scikit 的交叉验证,只需将其放入目标函数中即可(您甚至可以使用loss_variance跟踪交叉验证的方差)。
现在,为了真正回答这个问题,我相信您可以记录模型、参数、指标或传递给的目标函数内的任何内容hyperopt.fmin。MLFlow 将每次运行存储为主运行的子项,并且每次运行都可以有自己的工件。
所以你想要这样的东西:
def objective(params):
metrics = ...
classifier = SomeClassifier(**params)
cv = cross_validate(classifier, X_train, y_train, scoring = metrics)
scores = {metric: cv[f'test_{metric}'] for metric in metrics}
# log all the stuff here
mlflow.log_metric('...', scores[...])
mlflow.sklearn.log_model(classifier.fit(X_train, y_train))
return scores['some_loss'].mean()
space = hp.choice(...)
trials = SparkTrials(parallelism = ...)
with mlflow.start_run() as run:
best_result = fmin(fn = objective, space = space, algo = tpe.suggest, max_evals = 100, trials = trials)
Run Code Online (Sandbox Code Playgroud)