目录
决策树原理
二级目录
三级目录
Demo实现
构造数据集
#构造数据集
x_features=np.array([[-1,-2],[-2,-2,],[-3,-2],[1,3],[2,1],[3,2]])
y_label=np.array([0,1,0,1,0,1])
#调用逻辑回归模型
tree_clf=DecisionTreeClassifier()
#用逻辑回归模型拟合构造的数据集
tree_clf=tree_clf.fit(x_features,y_label)
模型可视化
#数据和模型可视化(要用到graphviz可视化库)
#可视化构造的数据样本点
plt.figure()
plt.scatter(x_features[:,0],x_features[:,1],c=y_label,s=50,cmap='viridis')
plt.title('Dataset')
plt.show()
决策树可视化
conda install python-graphviz
##可视化决策树
import graphviz
dot_data=tree.export_graphviz(tree_clf,out_file=None) #tree_clf决策树模型名称, out_file输出文件的句柄或名称,默认值是None
graph=graphviz.Source(dot_data) #调用graphviz的source方法解析数据
graph.render("pengunis") #生成决策树模型的可视化文件 https://www.cnblogs.com/pinard/p/6056319.html
模型预测
#模型预测
#创建新样本
x_features_new1=np.array([[0,-1]])
x_features_new2=np.array([[2,1]])
#在(训练集和测试集上?)分别利用训练好的模型进行预测
y_label_new1_predict=tree_clf.predict(x_features_new1)
y_label_new2_predict=tree_clf.predict(x_features_new2)
print('The New point 1 predict class:\n',y_label_new1_predict)
print('The New point 2 predict class:\n',y_label_new2_predict)
The New point 1 predict class:
[0]
The New point 2 predict class:
[0]
基于企鹅数据集的决策树实战
导入库和数据
函数库导入
#函数库导入
import numpy as np
import pandas as pd
#绘图函数库
import matplotlib.pyplot as plt
import seaborn as sns
数据集导入
选择企鹅数据(palmerpenguins)进行方法的尝试训练,该数据集一共包含8个变量,其中7个特征变量,1个目标分类变量。共有150个样本,目标变量为 企鹅的类别 其都属于企鹅类的三个亚属,分别是(Adélie, Chinstrap and Gentoo)。包含的三种种企鹅的七个特征,分别是所在岛屿,嘴巴长度,嘴巴深度,脚蹼长度,身体体积,性别以及年龄。
## 利用read_csv读取并转化为DataFrame格式
data=pd.read_csv('C:/Users/Administrator/LC python/datawhale/machine learning/DecisionTree/penguins_raw.csv')
##为了方便仅选取四个简单的特征
data = data[['Species','Culmen Length (mm)','Culmen Depth (mm)','Flipper Length (mm)','Body Mass (g)']]
#数据信息查看
data.info()
## 数据查看
data.head()
#填补数据的缺失值为-1
data=data.fillna(-1)
data.tail()
data['Species'].unique() #其对应的类别标签为'Adelie Penguin', 'Gentoo penguin', 'Chinstrap penguin'三种不同企鹅的类别。
array([‘Adelie Penguin (Pygoscelis adeliae)’,
‘Gentoo penguin (Pygoscelis papua)’,
‘Chinstrap penguin (Pygoscelis antarctica)’], dtype=object)
## 利用value_counts函数查看每个类别数量
pd.Series(data['Species']).value_counts()
data['Species'].nunique()
3
## 对于特征进行一些统计描述
data.describe()
可视化描述
#特征与标签组合的散点可视化
sns.pairplot(data=data,diag_kind='hist',hue='Species')
plt.show()
根据图像可以看出,区分能力都不咋的。
"""
为了方便我们将标签转化为数字
'Adelie Penguin (Pygoscelis adeliae)' ------0
'Gentoo penguin (Pygoscelis papua)' ------1
'Chinstrap penguin (Pygoscelis antarctica) ------2
"""
def trans(x):
if x==data['Species'].unique()[0]:
return 0
if x==data['Species'].unique()[1]:
return 1
if x==data['Species'].unique()[2]:
return 2
data['Species']=data['Species'].apply(trans)
#之前做的数据分析是将文本替换为数字后列出新的一列,这个是直接替换
data.head()
for col in data.columns:
if col !='Species':
sns.boxplot(x='Species',y=col,saturation=0.5,palette='pastel',data=data)#除Species列外画箱线图
plt.title(col)
plt.show()
# 选取其前三个特征绘制三维散点图
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')
data_class0 = data[data['Species']==0].values
data_class1 = data[data['Species']==1].values
data_class2 = data[data['Species']==2].values
# 'setosa'(0), 'versicolor'(1), 'virginica'(2)
ax.scatter(data_class0[:,0], data_class0[:,1],
data_class0[:,2],label=data['Species'].unique()[0])
ax.scatter(data_class1[:,0], data_class1[:,1],
data_class1[:,2],label=data['Species'].unique()[1])
ax.scatter(data_class2[:,0], data_class2[:,1],
data_class2[:,2],label=data['Species'].unique()[2])
plt.legend()
plt.show()
利用决策树模型进行二分类训练和预测
## 为了正确评估模型性能,将数据划分为训练集和测试集,并在训练集上训练模型,在测试集上验证模型性能。
from sklearn.model_selection import train_test_split
## 选择其类别为0和1的样本 (不包括类别为2的样本)
data_target_part = data[data['Species'].isin([0,1])][['Species']] #返回Species为0,1的布尔值为Ture,取Ture的值,构成列,取出这一列
data_features_part = data[data['Species'].isin([0,1])][['Culmen Length (mm)','Culmen Depth (mm)','Flipper Length (mm)','Body Mass (g)']]
#取出其对应的四个特征列,其输出就相当于target做索引
## 测试集大小为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data_features_part, data_target_part, test_size = 0.2, random_state = 2020)
Ps:看一下这些代码是什么意思,勤动手【爱心】
data[data['Species'].isin([0,1])]['Species'] #输出Series
data[data['Species'].isin([0,1])][['Species']] #输出DataFrame
data[data['Species'].isin([0,1])][['Culmen Length (mm)','Culmen Depth (mm)','Flipper Length (mm)','Body Mass (g)']]#对应的
ps结束。
## 从sklearn中导入决策树模型
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
## 定义 逻辑回归模型
clf = DecisionTreeClassifier(criterion='entropy')
# 在训练集上训练决策树模型
clf.fit(x_train, y_train)
## 可视化
import graphviz
dot_data = tree.export_graphviz(clf, out_file=None)
graph = graphviz.Source(dot_data)
graph.render("penguins")
‘penguins.pdf’
## 在训练集和测试集上分布利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics
## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))#分类准确率分数是指所有分类正确的百分比。分类准确率这一衡量分类器的标准比较容易理解,但是它不能告诉你响应值的潜在分布,并且它也不能告诉你分类器犯错的类型。
## 查看混淆矩阵 (预测值和真实值的各类情况统计矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test) #可以查看各类错误的类型
print('The confusion matrix result:\n',confusion_matrix_result)
# 利用热力图对于结果进行可视化,画出混淆矩阵的热力图
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()
可以看到模型的准确度为1。
利用决策树模型进行三分类训练和预测
## 测试集大小为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data[['Culmen Length (mm)','Culmen Depth
(mm)',
'Flipper Length (mm)','Body Mass (g)']], data[['Species']], test_size = 0.2,
random_state = 2020)
## 定义 逻辑回归模型
clf = DecisionTreeClassifier()
# 在训练集上训练逻辑回归模型
clf.fit(x_train, y_train)
## 在训练集和测试集上分布利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
## 由于逻辑回归模型是概率预测模型(前文介绍的 p = p(y=1|x,\theta)),所有我们可以利用
predict_proba 函数预测其概率
train_predict_proba = clf.predict_proba(x_train)
test_predict_proba = clf.predict_proba(x_test)
print('The test predict Probability of each class:\n',test_predict_proba)
## 其中第一列代表预测为0类的概率,第二列代表预测为1类的概率,第三列代表预测为2类的概率。
## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('The accuracy of the Logistic Regression
is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression
is:',metrics.accuracy_score(y_test,test_predict))
The test predict Probability of each class:
[[0. 0. 1.]
[0. 1. 0.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 1. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 1. 0.]
[0. 1. 0.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[1. 0. 0.]
[0. 0. 1.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[0. 0. 1.]
[0. 1. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[0. 0. 1.]
[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 1.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
[1. 0. 0.]
[1. 0. 0.]]
The accuracy of the Logistic Regression is: 0.9963636363636363
The accuracy of the Logistic Regression is: 0.9565217391304348
## 查看混淆矩阵
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)
# 利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()
123456789
10
The confusion matrix result:
[[30 1 0]
[ 0 23 0]
[ 2 0 13]]
1234