GridSearchCV 簡介
GridSearchCV,自動調(diào)參,設(shè)置好相應(yīng)參數(shù),就能給出最優(yōu)化的結(jié)果和參數(shù)。
class sklearn.grid_search.GridSearchCV(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch=‘2*n_jobs’, error_score=’raise’)[source]
Deprecated since version 0.18: This module will be removed in 0.20. Use sklearn.model_selection.GridSearchCV instead.
- estimator
選擇使用的分類器,并且傳入除需要確定最佳的參數(shù)之外的其他參數(shù)。
每一個(gè)分類器都需要一個(gè)scoring參數(shù),或者score方法:
如estimator=RandomForestClassifier(
min_samples_split=100,
min_samples_leaf=20,
max_depth=8,
max_features='sqrt',
random_state=10),
param_grid
需要最優(yōu)化的參數(shù)的取值,值為字典或者列表,例如:
param_grid =param_test1,
param_test1 = {'n_estimators':range(10,71,10)}。scoring=None
模型評價(jià)標(biāo)準(zhǔn),默認(rèn)None,這時(shí)需要使用score函數(shù);或者如scoring='roc_auc',
根據(jù)所選模型不同,評價(jià)準(zhǔn)則不同。字符串(函數(shù)名),或是可調(diào)用對象,
需要其函數(shù)簽名形如:scorer(estimator, X, y);如果是None,則使用estimator的誤差估計(jì)函數(shù)。n_jobs=1
n_jobs: 并行數(shù),int:個(gè)數(shù),-1:跟CPU核數(shù)一致, 1:默認(rèn)值cv=None
交叉驗(yàn)證參數(shù),默認(rèn)None,使用三折交叉驗(yàn)證。指定fold數(shù)量,默認(rèn)為3,也可以是yield產(chǎn)生訓(xùn)練/測試數(shù)據(jù)的生成器。
verbose=0, scoring=None
verbose:日志冗長度,int:冗長度,0:不輸出訓(xùn)練過程,1:偶爾輸出,>1:對每個(gè)子模型都輸出。pre_dispatch=‘2*n_jobs’
指定總共分發(fā)的并行任務(wù)數(shù)。當(dāng)n_jobs大于1時(shí),數(shù)據(jù)將在每個(gè)運(yùn)行點(diǎn)進(jìn)行復(fù)制,這可能導(dǎo)致OOM,
而設(shè)置pre_dispatch參數(shù),則可以預(yù)先劃分總共的job數(shù)量,使數(shù)據(jù)最多被復(fù)制pre_dispatch次return_train_score=’warn’
如果“False”,cv_results_屬性將不包括訓(xùn)練分?jǐn)?shù)。refit :默認(rèn)為True,程序?qū)越徊骝?yàn)證訓(xùn)練集得到的最佳參數(shù),重新對所有可用的訓(xùn)練集與開發(fā)集進(jìn)行,
作為最終用于性能評估的最佳模型參數(shù)。即在搜索參數(shù)結(jié)束后,用最佳參數(shù)結(jié)果再次fit一遍全部數(shù)據(jù)集。iid:默認(rèn)True,為True時(shí),默認(rèn)為各個(gè)樣本fold概率分布一致,誤差估計(jì)為所有樣本之和,而非各個(gè)fold的平均。
進(jìn)行預(yù)測的常用方法和屬性
- grid.fit():運(yùn)行網(wǎng)格搜索
- grid_scores_:給出不同參數(shù)情況下的評價(jià)結(jié)果
- best_params_:描述了已取得最佳結(jié)果的參數(shù)的組合
- best_score_:成員提供優(yōu)化過程期間觀察到的最好的評分
官網(wǎng)上貼例子
建立分類器clf時(shí),調(diào)用GridSearchCV()函數(shù),將上述參數(shù)列表的變量傳入函數(shù)。并且可傳入交叉驗(yàn)證cv參數(shù),設(shè)置為5折交叉驗(yàn)證。對訓(xùn)練集訓(xùn)練完成后調(diào)用best_params_變量,打印出訓(xùn)練的最佳參數(shù)組。
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC
# Loading the Digits dataset
digits = datasets.load_digits()
# To apply an classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images)
X = digits.images.reshape((n_samples, -1))
y = digits.target
# 將數(shù)據(jù)集分成訓(xùn)練集和測試集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0)
# 設(shè)置gridsearch的參數(shù)
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
#設(shè)置模型評估的方法.如果不清楚,可以參考上面的k-fold章節(jié)里面的超鏈接
scores = ['precision', 'recall']
for score in scores:
print("# Tuning hyper-parameters for %s" % score)
print()
#構(gòu)造這個(gè)GridSearch的分類器,5-fold
clf = GridSearchCV(SVC(), tuned_parameters, cv=5,
scoring='%s_weighted' % score)
#只在訓(xùn)練集上面做k-fold,然后返回最優(yōu)的模型參數(shù)
clf.fit(X_train, y_train)
print("Best parameters set found on development set:")
print()
#輸出最優(yōu)的模型參數(shù)
print(clf.best_params_)
print()
print("Grid scores on development set:")
print()
for params, mean_score, scores in clf.grid_scores_:
print("%0.3f (+/-%0.03f) for %r"
% (mean_score, scores.std() * 2, params))
print()
print("Detailed classification report:")
print()
print("The model is trained on the full development set.")
print("The scores are computed on the full evaluation set.")
print()
#在測試集上測試最優(yōu)的模型的泛化能力.
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
print()

【以下轉(zhuǎn)載】 sklearn中GridSearchCV如何設(shè)置嵌套參數(shù)
以adaboost為例,adaboost有自己的參數(shù),他的base_estimator指向一個(gè)弱學(xué)習(xí)器,這個(gè)弱學(xué)習(xí)器也包含自己的參數(shù),為了使用GridSearchCV我們需要使用嵌套參數(shù)。在sklearn中我們使用雙下劃線表示”__”,例如
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.grid_search import GridSearchCV
iris = datasets.load_iris()
param_grid = {"base_estimator__criterion": ["gini", "entropy"],
"base_estimator__splitter": ["best", "random"],
"n_estimators": [1, 2]}
dtc = DecisionTreeClassifier()
ada = AdaBoostClassifier(base_estimator=dtc)
X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1)
grid_search_ada = GridSearchCV(ada, param_grid=param_grid, cv=10)
grid_search_ada.fit(X, y)}