当前位置:   article > 正文

Python绘制多分类ROC曲线_决策树多分类roc

决策树多分类roc

目录

1 数据集介绍

1.1 数据集简介

1.2 数据预处理

 2随机森林分类

2.1 数据加载

2.2 参数寻优

2.3 模型训练与评估

3 绘制十分类ROC曲线

第一步,计算每个分类的预测结果概率

第二步,画图数据准备

第三步,绘制十分类ROC曲线


1 数据集介绍

1.1 数据集简介

分类数据集为某公司手机上网满意度数据集,数据如图所示,共7020条样本,关于手机满意度分类的特征有网络覆盖与信号强度、手机上网速度、手机上网稳定性等75个特征。

1.2 数据预处理

常规数据处理流程,详细内容见上期随机森林处理流程:

xxx 链接

  • 缺失值处理

  • 异常值处理

  • 数据归一化

  • 分类特征编码

处理完后的数据保存为 手机上网满意度.csv文件(放置文末)

 2随机森林分类

2.1 数据加载

第一步,导入包

  1. import pandas as pd
  2. import numpy as np
  3. from sklearn.ensemble import RandomForestClassifier# 随机森林回归
  4. from sklearn.model_selection import train_test_split,GridSearchCV,cross_val_score
  5. from sklearn.metrics import accuracy_score # 引入准确度评分函数
  6. from sklearn.metrics import mean_squared_error
  7. from sklearn import preprocessing
  8. import warnings
  9. warnings.filterwarnings('ignore')
  10. import matplotlib.pyplot as plt
  11. import matplotlib
  12. matplotlib.rc("font", family='Microsoft YaHei')

第二步,加载数据

  1. net_data = pd.read_csv('手机上网满意度.csv')
  2. Y = net_data.iloc[:,3]
  3. X= net_data.iloc[:, 4:]
  4. X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=200) # 随机数种子
  5. print(net_data.shape)
  6. net_data.describe()

2.2 参数寻优

第一步,对最重要的超参数n_estimators即决策树数量进行调试,通过不同数目的树情况下,在训练集和测试集上的均方根误差来判断

  1. ## 分析随着树数目的变化,在测试集和训练集上的预测效果
  2. rfr1 = RandomForestClassifier(random_state=1)
  3. n_estimators = np.arange(50,500,50) # 420,440,2
  4. train_mse = []
  5. test_mse = []
  6. for n in n_estimators:
  7. rfr1.set_params(n_estimators = n) # 设置参数
  8. rfr1.fit(X_train,Y_train) # 训练模型
  9. rfr1_lab = rfr1.predict(X_train)
  10. rfr1_pre = rfr1.predict(X_test)
  11. train_mse.append(mean_squared_error(Y_train,rfr1_lab))
  12. test_mse.append(mean_squared_error(Y_test,rfr1_pre))
  13. ## 可视化不同数目的树情况下,在训练集和测试集上的均方根误差
  14. plt.figure(figsize=(12,9))
  15. plt.subplot(2,1,1)
  16. plt.plot(n_estimators,train_mse,'r-o',label='trained MSE',color='darkgreen')
  17. plt.xlabel('Number of trees')
  18. plt.ylabel('MSE')
  19. plt.grid()
  20. plt.legend()
  21. plt.subplot(2,1,2)
  22. plt.plot(n_estimators,test_mse,'r-o',label='test MSE',color='darkgreen')
  23. index = np.argmin(test_mse)
  24. plt.annotate('MSE:'+str(round(test_mse[index],4)),
  25. xy=(n_estimators[index],test_mse[index]),
  26. xytext=(n_estimators[index]+2,test_mse[index]+0.000002),
  27. arrowprops=dict(facecolor='red',shrink=0.02))
  28. plt.xlabel('Number of trees')
  29. plt.ylabel('MSE')
  30. plt.grid()
  31. plt.legend()
  32. plt.tight_layout()
  33. plt.show()

以及最优参数和最高得分进行分析,如下所示

  1. ###调n_estimators参数
  2. ScoreAll = []
  3. for i in range(50,500,50):
  4. DT = RandomForestClassifier(n_estimators = i,random_state = 1) #,criterion = 'entropy'
  5. score = cross_val_score(DT,X_train,Y_train,cv=6).mean()
  6. ScoreAll.append([i,score])
  7. ScoreAll = np.array(ScoreAll)
  8. max_score = np.where(ScoreAll==np.max(ScoreAll[:,1]))[0][0] ##这句话看似很长的,其实就是找出最高得分对应的索引
  9. print("最优参数以及最高得分:",ScoreAll[max_score])
  10. plt.figure(figsize=[20,5])
  11. plt.plot(ScoreAll[:,0],ScoreAll[:,1],'r-o',label='最高得分',color='orange')
  12. plt.xlabel('n_estimators参数')
  13. plt.ylabel('分数')
  14. plt.grid()
  15. plt.legend()
  16. plt.show()

很明显,决策树个数设置在400的时候回归森林预测模型的测试集均方根误差最小,得分最高,效果最显著。因此,我们通过网格搜索进行小范围搜索,构建随机森林预测模型时选取的决策树个数为400。

第二步,在确定决策树数量大概范围后,搜索决策树的最大深度的最高得分,如下所示

  1. # 探索max_depth的最佳参数
  2. ScoreAll = []
  3. for i in range(4,14,2):
  4. DT = RandomForestClassifier(n_estimators = 400,random_state = 1,max_depth =i ) #,criterion = 'entropy'
  5. score = cross_val_score(DT,X_train,Y_train,cv=6).mean()
  6. ScoreAll.append([i,score])
  7. ScoreAll = np.array(ScoreAll)
  8. max_score = np.where(ScoreAll==np.max(ScoreAll[:,1]))[0][0]
  9. print("最优参数以及最高得分:",ScoreAll[max_score])
  10. plt.figure(figsize=[20,5])
  11. plt.plot(ScoreAll[:,0],ScoreAll[:,1])
  12. plt.xlabel('max_depth最佳参数')
  13. plt.ylabel('分数')
  14. plt.grid()
  15. plt.legend()
  16. plt.show()

决策树的深度最终设置为10。

2.3 模型训练与评估

  1. # 随机森林 分类模型
  2. model = RandomForestClassifier(n_estimators=400,max_depth=10,random_state=1) # min_samples_leaf=11
  3. # 模型训练
  4. model.fit(X_train, Y_train)
  5. # 模型预测
  6. y_pred = model.predict(X_test)
  7. print('训练集模型分数:', model.score(X_train,Y_train))
  8. print('测试集模型分数:', model.score(X_test,Y_test))
  9. print("训练集准确率: %.3f" % accuracy_score(Y_train, model.predict(X_train)))
  10. print("测试集准确率: %.3f" % accuracy_score(Y_test, y_pred))

绘制混淆矩阵:

  1. # 混淆矩阵
  2. from sklearn.metrics import confusion_matrix
  3. import matplotlib.ticker as ticker
  4. cm = confusion_matrix(Y_test, y_pred,labels=[1,2,3,4,5,6,7,8,9,10]) # ,
  5. print('混淆矩阵:\n', cm)
  6. labels=['1','2','3','4','5','6','7','8','9','10']
  7. from sklearn.metrics import ConfusionMatrixDisplay
  8. cm_display = ConfusionMatrixDisplay(cm,display_labels=labels).plot()

3 绘制十分类ROC曲线

第一步,计算每个分类的预测结果概率

  1. from sklearn.metrics import roc_curve,auc
  2. df = pd.DataFrame()
  3. pre_score = model.predict_proba(X_test)
  4. df['y_test'] = Y_test.to_list()
  5. df['pre_score1'] = pre_score[:,0]
  6. df['pre_score2'] = pre_score[:,1]
  7. df['pre_score3'] = pre_score[:,2]
  8. df['pre_score4'] = pre_score[:,3]
  9. df['pre_score5'] = pre_score[:,4]
  10. df['pre_score6'] = pre_score[:,5]
  11. df['pre_score7'] = pre_score[:,6]
  12. df['pre_score8'] = pre_score[:,7]
  13. df['pre_score9'] = pre_score[:,8]
  14. df['pre_score10'] = pre_score[:,9]
  15. pre1 = df['pre_score1']
  16. pre1 = np.array(pre1)
  17. pre2 = df['pre_score2']
  18. pre2 = np.array(pre2)
  19. pre3 = df['pre_score3']
  20. pre3 = np.array(pre3)
  21. pre4 = df['pre_score4']
  22. pre4 = np.array(pre4)
  23. pre5 = df['pre_score5']
  24. pre5 = np.array(pre5)
  25. pre6 = df['pre_score6']
  26. pre6 = np.array(pre6)
  27. pre7 = df['pre_score7']
  28. pre7 = np.array(pre7)
  29. pre8 = df['pre_score8']
  30. pre8 = np.array(pre8)
  31. pre9 = df['pre_score9']
  32. pre9 = np.array(pre9)
  33. pre10 = df['pre_score10']
  34. pre10 = np.array(pre10)

第二步,画图数据准备

  1. y_list = df['y_test'].to_list()
  2. pre_list=[pre1,pre2,pre3,pre4,pre5,pre6,pre7,pre8,pre9,pre10]
  3. lable_names=['1','2','3','4','5','6','7','8','9','10']
  4. colors1 = ["r","b","g",'gold','pink','y','c','m','orange','chocolate']
  5. colors2 = "skyblue"# "mistyrose","skyblue","palegreen"
  6. my_list = []
  7. linestyles =["-", "--", ":","-", "--", ":","-", "--", ":","-"]

第三步,绘制十分类ROC曲线

  1. plt.figure(figsize=(12,5),facecolor='w')
  2. for i in range(10):
  3. roc_auc = 0
  4. #添加文本信息
  5. if i==0:
  6. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=1)
  7. # 计算AUC的值
  8. roc_auc = auc(fpr, tpr)
  9. plt.text(0.3, 0.01, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  10. elif i==1:
  11. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=2)
  12. # 计算AUC的值
  13. roc_auc = auc(fpr, tpr)
  14. plt.text(0.3, 0.11, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  15. elif i==2:
  16. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=3)
  17. # 计算AUC的值
  18. roc_auc = auc(fpr, tpr)
  19. plt.text(0.3, 0.21, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  20. elif i==3:
  21. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=4)
  22. # 计算AUC的值
  23. roc_auc = auc(fpr, tpr)
  24. plt.text(0.3, 0.31, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  25. elif i==4:
  26. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=5)
  27. # 计算AUC的值
  28. roc_auc = auc(fpr, tpr)
  29. plt.text(0.3, 0.41, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  30. elif i==5:
  31. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=6)
  32. # 计算AUC的值
  33. roc_auc = auc(fpr, tpr)
  34. plt.text(0.6, 0.01, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  35. elif i==6:
  36. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=7)
  37. # 计算AUC的值
  38. roc_auc = auc(fpr, tpr)
  39. plt.text(0.6, 0.11, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  40. elif i==7:
  41. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=8)
  42. # 计算AUC的值
  43. roc_auc = auc(fpr, tpr)
  44. plt.text(0.6, 0.21, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  45. elif i==8:
  46. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=9)
  47. # 计算AUC的值
  48. roc_auc = auc(fpr, tpr)
  49. plt.text(0.6, 0.31, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  50. elif i==9:
  51. fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=10)
  52. # 计算AUC的值
  53. roc_auc = auc(fpr, tpr)
  54. plt.text(0.6, 0.41, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
  55. my_list.append(roc_auc)
  56. # 添加ROC曲线的轮廓
  57. plt.plot(fpr, tpr, color = colors1[i],linestyle = linestyles[i],linewidth = 3,
  58. label = "class:"+lable_names[i]) # lw = 1,
  59. #绘制面积图
  60. plt.stackplot(fpr, tpr, colors=colors2, alpha = 0.5,edgecolor = colors1[i]) # alpha = 0.5,
  61. # 添加对角线
  62. plt.plot([0, 1], [0, 1], color = 'black', linestyle = '--',linewidth = 3)
  63. plt.xlabel('1-Specificity')
  64. plt.ylabel('Sensitivity')
  65. plt.grid()
  66. plt.legend()
  67. plt.title("手机上网稳定性ROC曲线和AUC数值")
  68. plt.show()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/855776
推荐阅读
相关标签
  

闽ICP备14008679号