【问题标题】:cross validation + decision trees in sklearnsklearn中的交叉验证+决策树
【发布时间】:2016-05-07 22:12:03
【问题描述】:

尝试使用 sklearn 和 panads 创建具有交叉验证的决策树。

我的问题在下面的代码中,交叉验证拆分数据,然后我将其用于训练和测试。我将尝试通过设置不同的最大深度重新创建它 n 次来找到树的最佳深度。在使用交叉验证时,我应该使用 k 折叠 CV,如果是,我将如何在我拥有的代码中使用它?

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn import cross_validation

features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]

df = pd.read_csv('magic04.data',header=None,names=features)

df['class'] = df['class'].map({'g':0,'h':1})

x = df[features[:-1]]
y = df['class']

x_train,x_test,y_train,y_test = cross_validation.train_test_split(x,y,test_size=0.4,random_state=0)

depth = []
for i in range(3,20):
    clf = tree.DecisionTreeClassifier(max_depth=i)
    clf = clf.fit(x_train,y_train)
    depth.append((i,clf.score(x_test,y_test)))
print depth

这里是我正在使用的数据的链接,以防万一。 https://archive.ics.uci.edu/ml/datasets/MAGIC+Gamma+Telescope

【问题讨论】:

    标签: machine-learning decision-tree cross-validation


    【解决方案1】:

    在您的代码中,您正在创建一个静态训练-测试拆分。如果您想通过交叉验证选择最佳深度,您可以在 for 循环中使用 sklearn.cross_validation.cross_val_score

    您可以阅读sklearn's documentation了解更多信息。

    以下是您的 CV 代码更新:

    import numpy as np
    import pandas as pd
    from sklearn import tree
    from sklearn.cross_validation import cross_val_score
    from pprint import pprint
    
    features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]
    
    df = pd.read_csv('magic04.data',header=None,names=features)
    df['class'] = df['class'].map({'g':0,'h':1})
    
    x = df[features[:-1]]
    y = df['class']
    
    # x_train,x_test,y_train,y_test = cross_validation.train_test_split(x,y,test_size=0.4,random_state=0)
    depth = []
    for i in range(3,20):
        clf = tree.DecisionTreeClassifier(max_depth=i)
        # Perform 7-fold cross validation 
        scores = cross_val_score(estimator=clf, X=x, y=y, cv=7, n_jobs=4)
        depth.append((i,scores.mean()))
    print(depth)
    

    或者,您可以使用sklearn.grid_search.GridSearchCV,而不是自己编写 for 循环,特别是如果您想针对多个超参数进行优化。

    import numpy as np
    import pandas as pd
    from sklearn import tree
    from sklearn.model_selection import GridSearchCV
    
    features = ["fLength", "fWidth", "fSize", "fConc", "fConc1", "fAsym", "fM3Long", "fM3Trans", "fAlpha", "fDist", "class"]
    
    df = pd.read_csv('magic04.data',header=None,names=features)
    df['class'] = df['class'].map({'g':0,'h':1})
    
    x = df[features[:-1]]
    y = df['class']
    
    
    parameters = {'max_depth':range(3,20)}
    clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, n_jobs=4)
    clf.fit(X=x, y=y)
    tree_model = clf.best_estimator_
    print (clf.best_score_, clf.best_params_) 
    

    编辑:更改了 GridSearchCV 的导入方式以适应 learn2day 的评论。

    【讨论】:

    • +1 用于回答问题并建议网格搜索,这绝对是此类问题的更好做法
    • grid_search 自 0.18 起已弃用,自 0.20 起已删除。您现在应该使用来自sklearn.model_selectionGridSearchCV
    • @Dimosthenis 如何在 test 数据集上验证模型,因为所有数据都用于训练模型?
    • 或者我们应该将数据集的一部分保留为 test 数据集,即使用于交叉验证也不应该使用它
    • @Rookie_123 如果您选择使用交叉验证来优化模型的超参数,那么最好先进行训练/测试拆分,在训练集上训练并进行交叉验证,最后进行测试在您创建的第一个测试集上。 sklearn.model_selection.train_test_split 可以方便地进行火车测试拆分
    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 2013-01-24
    • 1970-01-01
    • 2011-01-19
    • 2019-03-25
    • 2016-05-05
    • 2012-12-31
    • 2021-05-27
    相关资源
    最近更新 更多