sklearn 中的交叉验证+决策树

cross validation + decision trees in sklearn

正在尝试使用 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

这是我正在使用的数据的 link,以防对任何人有帮助。 https://archive.ics.uci.edu/ml/datasets/MAGIC+Gamma+Telescope

在您的代码中,您正在创建静态训练-测试拆分。如果你想 select 通过交叉验证的最佳深度,你可以在 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 的评论。