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()

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
sklearn是一个Python的机器学习库,里面包含了很多机器学习算法的实现。其决策树是一个常用的分类和回归算法,在sklearn有完整的决策树实现。 使用sklearn决策树案例的步骤如下: 1. 导入必要的库和数据集:首先需要导入sklearn的decisiontree模块,以及其他可能需要的库,如numpy和pandas。然后,将准备好的数据集加载到程序。 2. 数据预处理:对于决策树模型,数据需要进行一定的预处理。这包括对数据进行缺失值处理、特征选择、特征缩放等。可以使用sklearn的preprocessing模块提供的函数进行处理。 3. 构建决策树模型:使用sklearn的DecisionTreeClassifier来构建决策树模型。可以设置树的深度、最小叶节点数、最小拆分样本数等参数。 4. 拟合模型:将准备好的训练数据传入fit函数进行模型拟合。模型会根据传入的数据进行训练,学习到数据的特征和标签之间的关系。 5. 预测和评估:使用训练好的模型对测试数据进行预测,得到预测结果。可以使用sklearn的predict函数来进行预测。然后,通过与真实标签进行比较,可以使用准确性、精确度、召回率等指标评估模型的性能。 6. 可视化决策树:如果希望可视化决策树,可以使用sklearn的export_graphviz函数生成Graphviz格式的决策树图形,然后使用Graphviz库进行展示。 总结来说,使用sklearn决策树案例需要导入库和数据集、预处理数据、构建模型、拟合模型、预测和评估模型,最后可以选择性地对决策树进行可视化。通过这个过程,我们可以使用决策树算法来解决分类和回归问题,并对模型性能进行评估和可视化展示。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值