在sklearn中的网格搜索交叉验证

6
2个回答

11

为什么不呢?

我邀请您查看GridsearchCV文档

示例

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score

param_grid = {'max_depth': np.arange(3, 10)}

tree = GridSearchCV(DecisionTreeClassifier(), param_grid)

tree.fit(xtrain, ytrain)
tree_preds = tree.predict_proba(xtest)[:, 1]
tree_performance = roc_auc_score(ytest, tree_preds)

print 'DecisionTree: Area under the ROC curve = {}'.format(tree_performance)

提取最佳参数:

tree.best_params_
Out[1]: {'max_depth': 5}

谢谢。那么,tree.best_params_是最好的特征名称吗?如果我的特征名称为['a','b','c','d','e'],我怎么知道最佳的特征名称呢? - Borys
tree.best_params_ 返回一个类似于 {'params1' : bestparam} 的字典。在这种情况下,你会得到例如 {'a' : 1, 'b' : 0.4, ...} - gowithefloww
如果你正在使用 GridSearchCV,难道不想使用整个数据集来拟合而不仅仅是训练子集吗?由于 GridSearchCV 在执行某种 k-fold CV 变体,只使用训练数据似乎浪费了数据。 - dsal1951
2
永远不要使用测试集来寻找超参数,因为这样会在训练阶段引入不应该有的信息,导致过拟合。当你没有验证样本时,交叉验证主要用于模拟测试集。 - gowithefloww
@gowithefloww 同意!使用测试集进行超参数调整是将目标绘制在箭头周围的完美例子。 - Foreever

2

这里是决策树网格搜索的代码

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV

def dtree_grid_search(X,y,nfolds):
    #create a dictionary of all values we want to test
    param_grid = { 'criterion':['gini','entropy'],'max_depth': np.arange(3, 15)}
    # decision tree model
    dtree_model=DecisionTreeClassifier()
    #use gridsearch to test all values
    dtree_gscv = GridSearchCV(dtree_model, param_grid, cv=nfolds)
    #fit model to data
    dtree_gscv.fit(X, y)
    return dtree_gscv.best_params_

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接