机器学习系列十九:sklearn-GridSearchCV

一、简介

GridSearchCV,它存在的意义就是自动调参,只要把参数输进去,就能给出最优化的结果和参数。但是这个方法适合于小数据集,一旦数据的量级上去了,很难得出结果。这个时候就是需要动脑筋了。数据量比较大的时候可以使用一个快速调优的方法——坐标下降。它其实是一种贪心算法:拿当前对模型影响最大的参数调优,直到最优化;再拿下一个影响最大的参数调优,如此下去,直到所有的参数调整完毕。

RandomizedSearchCV的使用方法其实是和GridSearchCV一致的,但它以随机在参数空间中采样的方式代替了GridSearchCV对于参数的网格搜索,在对于有连续变量的参数时,RandomizedSearchCV会将其当作一个分布进行采样这是网格搜索做不到的,它的搜索能力取决于设定的n_iter参数。

二、GridSearchCV模块

1.模块导入

from sklearn.model_selection import GridSearchCV

2.函数原型 

class sklearn.model_selection.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', return_train_score=True)

3.常用参数

estimator:所使用的分类器,如RandomForestClassifier、SVM等。

param_grid:值为字典或者列表,即需要最优化的参数的取值。

scoring :准确度评价标准,默认None,这时需要使用score函数;或者如scoring='roc_auc',根据所选模型不同,评价准则不同。

cv :交叉验证参数,默认None,使用三折交叉验证。指定fold数量,默认为3,也可以是yield训练/测试数据的生成器。

iid:默认True,为True时,默认为各个样本fold概率分布一致,误差估计为所有样本之和,而非各个fold的平均。

refit :默认为True,程序将会以交叉验证训练集得到的最佳参数,重新对所有可用的训练集与开发集进行,作为最终用于性能评估的最佳模型参数。即在搜索参数结束后,用最佳参数结果再次fit一遍全部数据集。

verbose:日志冗长度,int:冗长度,0:不输出训练过程,1:偶尔输出,>1:对每个子模型都输出。

n_jobs: 并行数,int:个数,-1:跟CPU核数一致, 1:默认值。

pre_dispatch:指定总共分发的并行任务数。当n_jobs大于1时,数据将在每个运行点进行复制,这可能导致OOM,而设置pre_dispatch参数,则可以预先划分总共的job数量,使数据最多被复制pre_dispatch次。

4.常用属性和方法

grid.fit():运行网格搜索
grid_scores_:给出不同参数情况下的评价结果
best_params_:描述了已取得最佳结果的参数的组合
best_score_:成员提供优化过程期间观察到的最好的评分

三、应用实例

1.GridSearchCV搜索SVM

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

# 将数据集分成训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.5, random_state=0)

# 设置gridsearch的参数
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
                     'C': [1, 10, 100, 1000]},
                    {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]

#设置模型评估的方法.如果不清楚,可以参考上面的k-fold章节里面的超链接
scores = ['precision', 'recall']

for score in scores:
    print("# Tuning hyper-parameters for %s" % score)


    #构造这个GridSearch的分类器,5-fold
    clf = GridSearchCV(SVC(), tuned_parameters, cv=5,
                       scoring='%s_weighted' % score)
    #只在训练集上面做k-fold,然后返回最优的模型参数
    clf.fit(X_train, y_train)

    print("Best parameters set found on development set:")

    #输出最优的模型参数
    print(clf.best_params_)

    print("Grid scores on development set:")

    for params, mean_score, scores in clf.grid_scores_:
        print("%0.3f (+/-%0.03f) for %r"
              % (mean_score, scores.std() * 2, params))


    print("Detailed classification report:")

    print("The model is trained on the full development set.")
    print("The scores are computed on the full evaluation set.")

    #在测试集上测试最优的模型的泛化能力.
    y_true, y_pred = y_test, clf.predict(X_test)
    print(classification_report(y_true, y_pred))

2.GridSearchCV搜索Adaboost设置嵌套参数

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.grid_search import GridSearchCV
from sklearn import datasets
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)
print(grid_search_ada.best_params_)
print(grid_search_ada.best_score_)

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
GridSearchCV是一个用于自动调参的工具,它通过遍历给定的参数组合来寻找最佳的模型参数。在参数中,scoring参数用于指定模型评估的指标。当scoring='r2'时,表示使用R^2作为模型评估的指标。 R^2(R-squared)是一种常用的回归模型评估指标,它表示模型对观测数据的拟合程度。R^2的取值范围在0到1之间,越接近1表示模型对数据的拟合程度越好。 下面是一个使用GridSearchCV进行参数调优并使用R^2作为评估指标的示例代码: ```python from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestRegressor # 定义参数网格 param_grid = { 'n_estimators': [10, 20, 30], 'max_depth': [None, 5, 10] } # 创建随机森林回归模型 forest_reg = RandomForestRegressor() # 创建GridSearchCV对象 grid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring='r2') # 在训练数据上进行参数搜索 grid_search.fit(X_train, y_train) # 输出最佳参数和对应的R^2值 print("Best parameters: ", grid_search.best_params_) print("Best R^2 score: ", grid_search.best_score_) ``` 在上述代码中,我们定义了一个参数网格param_grid,包含了n_estimators和max_depth两个参数的不同取值。然后创建了一个随机森林回归模型forest_reg,并使用GridSearchCV进行参数搜索,指定了cv=5表示使用5折交叉验证,scoring='r2'表示使用R^2作为评估指标。最后输出了最佳参数和对应的R^2值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值