如何为CV保留多个模型的字典(并在循环中使用它们)

时间:2018-10-31 10:59:38

标签: python machine-learning scikit-learn cross-validation

我希望有一个流程,该流程可以为我提供一系列机器学习模型及其准确性得分,但仅针对能够提供该类型模型最佳结果的参数集。

例如,这里只是XGBoost的简历:

数据集:

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
data = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])

from sklearn.model_selection import train_test_split
X = data.drop(['target'], axis=1)
y = data['target']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

查找最佳参数的功能:

from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score, make_scorer
accu = make_scorer(accuracy_score) # I will be using f1 in future

def predict_for_best_params(alg, X_train, y_train, X_test):
    params = {'n_estimators': [200, 300, 500]}
    clf = GridSearchCV(alg, params, scoring = accu, cv=2)
    clf.fit(X_train, y_train)
    print(clf.best_estimator_)
    y_pred = clf.predict(X_test)
    return y_pred

在一种模型上使用它:

from xgboost import XGBClassifier
alg = [XGBClassifier()]
y_pred = predict_for_best_params(alg[0], X_train, y_train, X_test)

from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, y_pred))

我想要实现的目标是:

from xgboost import XGBClassifier
from sklearn.ensemble import RandomForestClassifier

alg = [XGBClassifier(), RandomForrest()] # list of many of them

alg_params = {'XGBClassifier': [{'n_estimators': [200, 300, 500]}],
             'RandomForrest': [{'max_depth ': [1, 2, 3, 4]}]}

def predict_for_best_params(alg, X_train, y_train, X_test, params):
    clf = GridSearchCV(alg, params, scoring = accu, cv=2)
    clf.fit(X_train, y_train)
    print(clf.best_estimator_)
    y_pred = clf.predict(X_test)
    return y_pred

for algo in alg:
    params = alg_params[str(algo)][0] #this won't work because str(algo) <> e.g. XGBClassifier() but XGBClassier(all default params)
    y_pred = predict_for_best_params(algo, X_train, y_train, X_test, params)
    print('{} accuracy is: {}'.format(algo, accuracy_score(y_test, y_pred)))

这是实现它的好方法吗?

1 个答案:

答案 0 :(得分:2)

如果您只担心如何放置钥匙,则可以使用

params = alg_params[alg.__class__.__name__][0] 

这应该仅返回alg对象的类名

对于另一种方法,您可以看看我的其他答案:

该答案利用了GridSearchCV可以采用参数组合字典列表的事实,其中每个列表将单独扩展。但请注意以下几点:

  • 如果使用for-loop(使用多重处理),这可能比当前的n_jobs > 1快。
  • 然后您可以使用已完成的cv_results_的{​​{1}}属性来分析分数。
  • 要为各个估算器计算GridSearchCV,您可以过滤y_pred(也许通过将其导入cv_results_),然后再次使用最合适的参数对估算器进行拟合,然后然后计算y_pred。但是应该很容易。