python决策树分类 导入数据集_python中使用scikit-learn和pandas决策树进行iris鸢尾花数据分类建模和交叉验证...

交叉验证

获取数据

接下来,让我们使用上面设置的搜索方法来找到合适的参数设置。首先进行一些初步准备-获取数据并构建目标数据:

print("\n-- get data:")

df = get_iris_data()

print("")

features = ["SepalLength", "SepalWidth",

"PetalLength", "PetalWidth"]

df, targets = encode_target(df, "Name")

y = df["Target"]

X = df[features]

-- get data:

-- iris.csv found locally

blog_14154cb430102yqnh.html

第一次交叉验证

在下面的所有示例中,我将使用10倍交叉验证。

将数据分为10部分

拟合9个部分

其余部分的测试准确性

使用当前参数设置,在所有组合上重复此操作,以产生十个模型精度估计。通常会报告十个评分的平均值和标准偏差。

print("-- 10-fold cross-validation "

"[using setup from previous post]")

dt_old = DecisionTreeClassifier(min_samples_split=20,

random_state=99)

dt_old.fit(X, y)

scores = cross_val_score(dt_old, X, y, cv=10)

print("mean: {:.3f} (std: {:.3f})".format(scores.mean(),

scores.std()),

end="\n\n" )

-- 10-fold cross-validation [using setup from previous post]

mean: 0.960 (std: 0.033)

blog_14154cb430102yqnh.html

0.960还不错。这意味着平均准确性(使用经过训练的模型进行正确分类的百分比)为96%。该精度非常高,但是让我们看看是否可以找到更好的参数。

网格搜索的应用

首先,我将尝试网格搜索。字典para_grid提供了要测试的不同参数设置。

print("-- Grid Parameter Search via 10-fold CV")

dt = DecisionTreeClassifier()

ts_gs = run_gridsearch(X, y, dt, param_grid, cv=10)

-- Grid Parameter Search via 10-fold CV

GridSearchCV took 5.02 seconds for 288 candidate parameter settings.

Model with rank: 1

Mean validation score: 0.967 (std: 0.033)

Parameters: {'min_samples_split': 10, 'max_leaf_nodes': 5,

'criterion': 'gini', 'max_depth': None, 'min_samples_leaf': 1}

Model with rank: 2

Mean validation score: 0.967 (std: 0.033)

Parameters: {'min_samples_split': 20, 'max_leaf_nodes': 5,

'criterion': 'gini', 'max_depth': None, 'min_samples_leaf': 1}

Model with rank: 3

Mean validation score: 0.967 (std: 0.033)

Parameters: {'min_samples_split': 10, 'max_leaf_nodes': 5,

'criterion': 'gini', 'max_depth': 5, 'min_samples_leaf': 1}

blog_14154cb430102yqnh.html

在大多数运行中,各种参数设置的平均值为0.967。这意味着从96%改善到96.7%!我们可以看到最佳的参数设置ts_gs,如下所示:

print("\n-- Best Parameters:")

for k, v in ts_gs.items():

print("parameter: {:<20s} setting: {}".format(k, v))

-- Best Parameters:

parameter: min_samples_split setting: 10

parameter: max_leaf_nodes setting: 5

parameter: criterion setting: gini

parameter: max_depth setting: None

parameter: min_samples_leaf setting: 1

blog_14154cb430102yqnh.html

并复制交叉验证结果:

# test the retuned best parameters

print("\n\n-- Testing best parameters [Grid]...")

dt_ts_gs = DecisionTreeClassifier(**ts_gs)

scores = cross_val_score(dt_ts_gs, X, y, cv=10)

print("mean: {:.3f} (std: {:.3f})".format(scores.mean(),

scores.std()),

end="\n\n" )

-- Testing best parameters [Grid]...

mean: 0.967 (std: 0.033)

blog_14154cb430102yqnh.html

接下来,让我们使用获取最佳树的伪代码:

print("\n-- get_code for best parameters [Grid]:", end="\n\n")

dt_ts_gs.fit(X,y)

get_code(dt_ts_gs, features, targets)

-- get_code for best parameters [Grid]:

if ( PetalWidth <= 0.800000011921 ) {

return Iris-setosa ( 50 examples )

}

else {

if ( PetalWidth <= 1.75 ) {

if ( PetalLength <= 4.94999980927 ) {

if ( PetalWidth <= 1.65000009537 ) {

return Iris-versicolor ( 47 examples )

}

else {

return Iris-virginica ( 1 examples )

}

}

else {

return Iris-versicolor ( 2 examples )

return Iris-virginica ( 4 examples )

}

}

else {

return Iris-versicolor ( 1 examples )

return Iris-virginica ( 45 examples )

}

}

blog_14154cb430102yqnh.html

我们还可以制作决策树的图形:

visualize_tree(dt_ts_gs, features, fn="grid_best")

blog_14154cb430102yqnh.html

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE5NjAwMjkx,size_16,color_FFFFFF,t_70blog_14154cb430102yqnh.html

随机搜索的应用

接下来,我们尝试使用随机搜索方法来查找参数。在此示例中,我使用288个样本,以便测试的参数设置数量与上面的网格搜索相同:

与网格搜索一样,这通常会找到平均精度为0.967或96.7%的多个参数设置。如上所述,最佳交叉验证的参数为:

print("\n-- Best Parameters:")

for k, v in ts_rs.items():

print("parameters: {:<20s} setting: {}".format(k, v))

-- Best Parameters:

parameters: min_samples_split setting: 12

parameters: max_leaf_nodes setting: 5

parameters: criterion setting: gini

parameters: max_depth setting: 19

parameters: min_samples_leaf setting: 1

blog_14154cb430102yqnh.html

并且,我们可以再次测试最佳参数:

# test the retuned best parameters

)

-- Testing best parameters [Random]...

mean: 0.967 (std: 0.033)

blog_14154cb430102yqnh.html

blog_14154cb430102yqnh.html

要查看决策树是什么样的,我们可以生成伪代码以获得最佳随机搜索结果

并可视化树

visualize_tree(dt_ts_rs, features, fn="rand_best")

blog_14154cb430102yqnh.html

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE5NjAwMjkx,size_16,color_FFFFFF,t_70blog_14154cb430102yqnh.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值