Python实现鸢尾花分类任务的决策树算法

鸢尾花数据集介绍

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4X8jRzcC-1682471513133)(attachment:4DF91FF95586A48821F095FEB824B992.jpg)]

一:读取数据

from sklearn.datasets import load_iris
# 导入数据集Iris
iris = load_iris() #导入数据
iris_feature= iris.data #特征数据
iris_target = iris.target #分类数据
# print(iris.data)  # 输出数据
print(type(iris))
print(type(iris_feature))
print(type(iris_target))  # numpy 数据类型
<class 'sklearn.utils.Bunch'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
# numpy数据查看--索引
print(iris_feature[2])
print(iris_feature[2,1])
[4.7 3.2 1.3 0.2]
3.2

二:鸢尾花类别

target介绍

# print(iris.data)  # 输出数据
print(iris.target) #输出真实标签
print(len(iris.target)) #样本个数
print(iris.data.shape)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]
150
(150, 4)

三:数据可视化

1:绘制直方图

import pandas as pd
# 将特征的numpy数据转换为pandas数据
names=['length_sepal','width_speal','petal_length','petal_width ']
d_iris_feature = pd.DataFrame(iris_feature, columns=names)
d_iris_target=pd.DataFrame(iris_target,columns=['label_'])
print(d_iris_feature.head())
print(d_iris_target.head())

# 描述性分析
print(d_iris_feature.describe())

# hist(),输出各个特征对比的直方图
d_iris_feature.hist()
   length_sepal  width_speal  petal_length  petal_width 
0           5.1          3.5           1.4           0.2
1           4.9          3.0           1.4           0.2
2           4.7          3.2           1.3           0.2
3           4.6          3.1           1.5           0.2
4           5.0          3.6           1.4           0.2
   label_
0       0
1       0
2       0
3       0
4       0
       length_sepal  width_speal  petal_length  petal_width 
count    150.000000   150.000000    150.000000    150.000000
mean       5.843333     3.057333      3.758000      1.199333
std        0.828066     0.435866      1.765298      0.762238
min        4.300000     2.000000      1.000000      0.100000
25%        5.100000     2.800000      1.600000      0.300000
50%        5.800000     3.000000      4.350000      1.300000
75%        6.400000     3.300000      5.100000      1.800000
max        7.900000     4.400000      6.900000      2.500000





array([[<AxesSubplot:title={'center':'length_sepal'}>,
        <AxesSubplot:title={'center':'width_speal'}>],
       [<AxesSubplot:title={'center':'petal_length'}>,
        <AxesSubplot:title={'center':'petal_width '}>]], dtype=object)


2.png)]

四:训练和分类

1:划分训练集和测试集

构建训练集和测试集,分别保存在X_train,y_train,X_test,y_test

from sklearn.model_selection import train_test_split

from sklearn.model_selection import train_test_split

for i in range(1000):
	X_train, X_test, y_train, y_test = train_test_split(d_iris_feature,d_iris_target, test_size=0.3)  
    # 不要设置随机种子random_state保证每次划分的随机性
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
(105, 4)
(45, 4)
(105, 1)
(45, 1)
# 构造训练集和测试集
# <pre name="code" class="python"><span style="font-size:14px;">
from sklearn.model_selection import train_test_split

# 交叉验证
X_train,X_test,y_train,y_test=train_test_split(d_iris_feature,d_iris_target,random_state=1)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
# 默认为75%为训练,25%为测试
(112, 4)
(38, 4)
(112, 1)
(38, 1)
print(X_train)
     length_sepal  width_speal  petal_length  petal_width 
54            6.5          2.8           4.6           1.5
108           6.7          2.5           5.8           1.8
112           6.8          3.0           5.5           2.1
17            5.1          3.5           1.4           0.3
119           6.0          2.2           5.0           1.5
..            ...          ...           ...           ...
133           6.3          2.8           5.1           1.5
137           6.4          3.1           5.5           1.8
72            6.3          2.5           4.9           1.5
140           6.7          3.1           5.6           2.4
37            4.9          3.6           1.4           0.1

[112 rows x 4 columns]
print(y_train)
     label_
54        1
108       2
112       2
17        0
119       2
..      ...
133       2
137       2
72        1
140       2
37        0

[112 rows x 1 columns]

2:训练和分类

from sklearn.tree import DecisionTreeClassifier

DecisionTreeClassifier()

DecisionTreeClassifier(criterion=‘entropy’, min_samples_leaf=3)函数为创建一个决策树模型,其函数的参数含义如下所示

class_weight : 指定样本各类别的的权重,主要是为了防止训练集某些类别的样本过多导致训练的决策树过于偏向这些类别。这里可以自己指定各个样本的权重,如果使用“balanced”,则算法会自己计算权重,样本量少的类别所对应的样本权重会高。

criterion : gini或者entropy,前者是基尼系数,后者是信息熵;

max_depth : int or None, optional (default=None) 设置决策随机森林中的决策树的最大深度,深度越大,越容易过拟合,推荐树的深度为:5-20之间;

max_features: None(所有),log2,sqrt,N 特征小于50的时候一般使用所有的;

max_leaf_nodes : 通过限制最大叶子节点数,可以防止过拟合,默认是"None”,即不限制最大的叶子节点数。

min_impurity_split: 这个值限制了决策树的增长,如果某节点的不纯度(基尼系数,信息增益,均方差,绝对差)小于这个阈值则该节点不再生成子节点。即为叶子节点 。

min_samples_leaf : 这个值限制了叶子节点最少的样本数,如果某叶子节点数目小于样本数,则会和兄弟节点一起被剪枝。

min_samples_split : 设置结点的最小样本数量,当样本数量可能小于此值时,结点将不会在划分。

min_weight_fraction_leaf: 这个值限制了叶子节点所有样本权重和的最小值,如果小于这个值,则会和兄弟节点一起被剪枝默认是0,就是不考虑权重问题。

presort :

splitter : best or random 前者是在所有特征中找最好的切分点 后者是在部分特征中,默认的”best”适合样本量不大的时候,而如果样本数据量非常大,此时决策树构建推荐”random” 。

from  sklearn.tree import DecisionTreeClassifier

#clf:决策树对象
clf=DecisionTreeClassifier(criterion='entropy', min_samples_leaf=3) #
# 调用对象训练数据
clf.fit(X_train,y_train)
print(clf)

#预测
predicted=clf.predict(X_test)
print(predicted)

DecisionTreeClassifier(criterion='entropy', min_samples_leaf=3)
[0 1 1 0 2 1 2 0 0 2 1 0 2 1 1 0 1 1 0 0 1 1 2 0 2 1 0 0 1 2 1 2 1 2 2 0 1
 0]

3:算法精度

# from sklearn.metrics import roc_curve

# fpr,tpr,threshold=roc_curve(y_test,predicted)

# 多分类不用RoC曲线评估

使用ROC曲线评估分类模型是非常通用的手段,但是,使用它的时候要注意两点:

1、分类的类型。

必须为数值型。

2、只针对二分类问题。

ROC曲线是根据一系列不同的二分类方式(分界值或决定阈),以真阳性率(灵敏度)为纵坐标,假阳性率(1-特异度)为横坐标绘制的曲线。传统的诊断试验评价方法有一个共同的特点,必须将试验结果分为两类,再进行统计分析。

3.1 accuracy_score

sklearn.metrics.accuracy_score(y_true, y_pred, normalize=True, sample_weight=None)

normalize:默认值为True,返回正确分类的比例;如果为False,返回正确分类的样本数

3.2 f1_score()

from sklearn import metrics

# 计算模型评估指标
acc = metrics.accuracy_score(y_test, predicted)
print('acc: '+str(acc))
f1 = metrics.f1_score(y_test, predicted,average='micro')
print('f1: '+str(f1))

# class_names = np.unique(y_train)
# y_binarize = label_binarize(y_test, classes=class_names)
# y_fit=label_binarize(y_pred, classes = class_names)
# fpr, tpr, _= metrics.roc_curve(y_binarize.ravel(),y_fit.ravel())
# auc = metrics.auc(fpr, tpr)
# print('auc: '+str(auc))

acc: 0.9736842105263158
f1: 0.9736842105263158

4:

predicted.reshape(len(predicted))
array([0, 1, 1, 0, 2, 1, 2, 0, 0, 2, 1, 0, 2, 1, 1, 0, 1, 1, 0, 0, 1, 1,
       2, 0, 2, 1, 0, 0, 1, 2, 1, 2, 1, 2, 2, 0, 1, 0])
import numpy as np

type(X_test)
# scatter()的输入为array
X_test_=np.array(X_test)
# X_test为datafram数据,需要转换为numpy 的数组array形式
# 获取花卉的两列数据集

# 绘图
import matplotlib.pyplot as plt
plt.scatter(X_test_[:,0],X_test_[:,1], c=predicted.reshape(len(predicted)), marker='x')
plt.show()

# X_test_[:,0],X_test_[:,1]用前两个特征画图,没有降维

物联沃分享整理
物联沃-IOTWORD物联网 » Python实现鸢尾花分类任务的决策树算法

发表评论