这个cart决策树于spyder(python3.8)运行
我想要的是train的索引为3并绘制出结果图
但是系统报错索引超限
希望能帮助我使得这个程序顺利运行
code
#构建并测试CART决策树模型
import pandas as pd
import matplotlib.pyplot as plt #导入作图库
from random import shuffle
from sklearn.tree import DecisionTreeClassifier #导入决策树模型
from sklearn.metrics import roc_curve #导入ROC曲线函数
from sklearn.metrics import confusion_matrix #导入混淆矩阵函数
def cm_plot(y, yp):
cm = confusion_matrix(y, yp) #混淆矩阵
plt.matshow(cm, cmap=plt.cm.Greens) #画混淆矩阵图
plt.colorbar() #颜色标签
for x in range(len(cm)): #数据标签
for y in range(len(cm)):
plt.annotate(cm[x,y], xy=(x, y), horizontalalignment='center', verticalalignment='center')
plt.ylabel('True label') #坐标轴标签
plt.xlabel('Predicted label') #坐标轴标签
return plt
data = pd.read_excel('C:/Users/one/Documents/GitHub/Python 数据挖掘之电力窃漏电用户自动识别/输出.xls')
data = data.values
shuffle(data)
p = 0.8 #设置训练数据比例
train = data[:int(len(data)*p),:] #前80%为训练集
test = data[int(len(data)*p):,:] #后20%为测试集
#构建CART决策树模型
tree = DecisionTreeClassifier() #建立决策树模型
tree.fit(train[:,:3], train[:,3]) #训练
#保存模型
import joblib
joblib.dump(tree, 'tmp/tree.pkl')
cm_plot(train[:,3], tree.predict(train[:,:3])).show() #显示混淆矩阵可视化结果
#注意到Scikit-Learn使用predict方法直接给出预测结果。
fpr, tpr, thresholds = roc_curve(test[:,3], tree.predict_proba(test[:,:3])[:,1], pos_label=1)
plt.plot(fpr, tpr, linewidth=2, label = 'ROC of CART', color = 'green') #作出ROC曲线
plt.xlabel('False Positive Rate') #坐标轴标签
plt.ylabel('True Positive Rate') #坐标轴标签
plt.ylim(0,1.05) #边界范围
plt.xlim(0,1.05) #边界范围
plt.legend(loc=4) #图例
plt.show() #显示作图结果