sklearn中决策树的使用

本文通过使用Python的sklearn库,详细介绍了如何对蘑菇数据集进行预处理、特征编码、数据标准化,并利用决策树模型进行分类预测。文中还探讨了特征选择的重要性,展示了如何根据特征重要性进行选择,并最终生成决策树的可视化图表。

1、数据准备

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score

dpath = './data/'
data = pd.read_csv(dpath+"mushrooms.csv")
data.head()
data.info()
data['class'].unique()
data.shape

2、特征编码

很多模型需要数值型的输入,比如Logisstic回归、xgboost.......

LableEncoder编码后会进行排序,因此是有序的,适用于logistic回归。

而颜色等特征是没有序关系,决策树等模型不care排序,也可以试试OneHotEncoder

from sklearn.preprocessing import LabelEncoder
labelencoder=LabelEncoder()
for col in data.columns:
    data[col] = labelencoder.fit_transform(data[col])

data.head()

y = data['class']    #用列名访问更直观
X = data.drop('class', axis = 1)

3、数据标准化

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=4)

columns = X_train.columns

# 数据标准化
from sklearn.preprocessing import StandardScaler

# 分别初始化对特征和目标值的标准化器
ss_X = StandardScaler()
ss_y = StandardScaler()

# 分别对训练和测试数据的特征以及目标值进行标准化处理
X_train = ss_X.fit_transform(X_train)
X_test = ss_X.transform(X_test)

4、决策树

from sklearn.tree import DecisionTreeClassifier

model_tree = DecisionTreeClassifier()
model_tree.fit(X_train, y_train)
y_prob = model_tree.predict_proba(X_test)[:,1] # This will give you positive class prediction probabilities  
y_pred = np.where(y_prob > 0.5, 1, 0) # This will threshold the probabilities to give class predictions.
model_tree.score(X_test, y_pred)
print('The AUC of default Desicion Tree is',roc_auc_score(y_test,y_pred))

#查看变量的重要性排序
df = pd.DataFrame({"columns":list(columns), "importance":list(model_tree.feature_importances_.T)})
df.sort_values(by=['importance'],ascending=False)

plt.bar(range(len(model_tree.feature_importances_)), model_tree.feature_importances_)
plt.show()

5、根据特征重要性做特征选择

from numpy import sort
from sklearn.feature_selection import SelectFromModel

# Fit model using each importance as a threshold
thresholds = sort(model_tree.feature_importances_)
for thresh in thresholds:
  # select features using threshold
  selection = SelectFromModel(model_tree, threshold=thresh, prefit=True)
  select_X_train = selection.transform(X_train)

  # train model
  selection_model = DecisionTreeClassifier()
  selection_model.fit(select_X_train, y_train)
    
# eval model
  select_X_test = selection.transform(X_test)
  y_pred = selection_model.predict(select_X_test)
  predictions = [round(value) for value in y_pred]
  accuracy = accuracy_score(y_test, predictions)
  print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (thresh, select_X_train.shape[1],
      accuracy*100.0))

# Fit model using the best threshhold
thresh = 0.020
selection = SelectFromModel(model_tree, threshold=thresh, prefit=True)
select_X_train = selection.transform(X_train)

# train model
selection_model = DecisionTreeClassifier()
selection_model.fit(select_X_train, y_train)

6、导出决策树图

import graphviz
from sklearn import tree
tree.export_graphviz(model_tree, out_file='best_tree.dot') 

#liunx系统可在  best_tree.dot所在目录下执行 dot -Tpng best_tree.dot -o best_tree.png  命令
#将决策树dot文件转化成png图
#查看决策树
from PIL import Image
img=Image.open('best_tree.png')
plt.imshow(img)
plt.show()

 

<think>好的,我需要帮助用户找到在Python中使用sklearn库实现决策树的示例代码。根据用户提供的引用内容,有几个相关的引用可能有用。 首先,引用[1]提到了一个基本的DecisionTreeClassifier的初始化、训练和评分过程。代码示例包括dt_clf = DecisionTreeClassifier(),fit方法以及score方法。这应该是一个简单的示例,适合用户快速上手。 然后,引用[2]展示了如何导出可视化决策树使用了plot_tree函数,并结合matplotlib进行显示。这部分代码不仅训练模型,还包含了可视化的步骤,可能对用户有帮助,特别是如果他们想查看生成的决策树结构的话。 引用[4]提供了更详细的代码示例,包括加载数据、训练模型、预测、概率预测以及导出文本格式的决策树。此外,还提到了需要安装graphviz来生成更生动的树结构图,但用户可能需要额外安装这个库,这一点需要注意。 引用[5]虽然主要关于数据分析的步骤,但提到了导入必要的库,这可能对用户设置环境有帮助,不过可能不是用户当前问题的核心。 接下来,我需要将这些信息整合成一个清晰的步骤说明,并给出对应的代码示例。用户可能需要一个完整的端到端示例,从数据加载到模型评估。因此,结合引用[2]和[4],可以构造一个使用鸢尾花数据集的示例,包括模型训练、预测、可视化和文本输出。 需要注意的是,用户可能对如何安装必要的库有疑问,但根据引用[3]和[4],可能需要安装scikit-learn、matplotlib和graphviz。不过用户的问题主要是示例代码,所以可能不需要详细安装步骤,除非用户提到环境问题。 另外,需要确保代码的正确性,比如正确导入库,正确使用fit和predict方法。引用[4]中的export_text函数可以用来生成文本形式的树结构,这也是一个有用的部分。 最后,生成相关问题,可能需要围绕决策树的参数调整、可视化优化、模型评估等方面提问,参考用户提供的示例中的相关问题结构。</think>在Python中使用scikit-learn实现决策树可分为以下步骤: ### 一、基础实现示例 ```python # 导入必要库 from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier, plot_tree from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # 加载数据集 iris = load_iris() X, y = iris.data, iris.target # 划分训练集/测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 创建决策树分类器 dt_clf = DecisionTreeClassifier(max_depth=3) # 限制树深度防止过拟合 # 训练模型 dt_clf.fit(X_train, y_train) # 评估模型 print(f"测试集准确率:{dt_clf.score(X_test, y_test):.2%}") # 输出类似:测试集准确率:95.00% ``` ### 二、可视化实现(需安装graphviz) ```python # 绘制决策树 plt.figure(figsize=(20,12)) plot_tree(dt_clf, filled=True, feature_names=iris.feature_names, class_names=iris.target_names) plt.show() ``` ### 三、文本格式输出 ```python from sklearn.tree import export_text # 生成文本格式决策树 tree_rules = export_text(dt_clf, feature_names=iris.feature_names) print(tree_rules) ``` 输出示例: |--- petal width (cm) <= 0.80 | |--- class: 0 |--- petal width (cm) > 0.80 | |--- petal width (cm) <= 1.75 | | |--- class: 1 | |--- petal width (cm) > 1.75 | | |--- class: 2 [^4] 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值