模型训练之决策树、随机森林、提升树


本节内容包括:

  • 树模型的sklearn使用:Decision Tree\Random Forest\GBDT
  • 分类评价指标说明:Accuracy\TPR和FPR\ ROC曲线\ PR曲线\ AP\F1 score
  • 交叉验证:k折交叉验证\留一交叉验证
  • 超参搜索:网格搜索\随机搜索\hyperopt自动化搜索

目录

1.导入工具包:

import numpy as np
import pandas as pd
from matplotlib.pyploy as plt 
import time
import warnings
warnings.filterwarnings('ignore')

2.实验数据生成

生成实验数据,make_blobs会根据用户指定的样本总量、中心点个数、分布的离散程度等来生成想要的数据。
函数make_blobs的参数:

  • n_samples:样本总量;
  • centers:簇团中心点个数;
  • random_state:确定随机种子,保证每次数据都是一样的;
  • cluster_std:每个簇团的离散程度,越大越分散,越小越集中。
from sklearn.datasets.samples_generator import make_blobs
X,y=make_blobs(n_samples=500,centers=2,random_state=21,cluster_std=3.5)
# 画出数据散点图
plt.scatter(X[:,0],X[:,1],c=y,s=50)
plt.show()

在这里插入图片描述

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.3,random_state=32)
print(X_train.shape,X_test.shape)
(350, 2) (150, 2)# print 输出结果

4.树模型的使用

所使用到的机器学习模型包括:

  • 决策树模型(Decision Tree)
  • 随机森林(Random Forest)
  • 梯度提升树(GBDT),最常用的框架lightGBM

4.1 Decision Tree

from sklearn.tree import DecisionTreeClassifier
dt=DecisionTreeClassifier(
	critterion='entropy',
	splitter='best',
	max_depth=4,
	max_leaf_nodes=12,
	min_samples_leaf=30,
	presort=True,# 此参数项在实际代码运行时可以不写,默认为False
)
dt.fit(X_train,y_train)
y_pred_dt=dt.predict(X_test)
# 画出样本的散点图
plt.scatter(X_test[:,0],X_test[:,1],c=y_pred_dt,s=20)
plt.title('Decision tree classification result')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

在这里插入图片描述

4.2 Random Forest

from sklearn.ensemble import RandomForestClassifier
rf=RandomForestClassifier(
	n_estimators=10,
	criterion='entropy',
	max_depth=4,
	max_leaf_nodes=12,
	min_samples_leaf=30,
	bootstrap=True,
	n_jobs=1,
	max_samples=0.8
)
rf.fit(X_train,y_train)
y_pred_rf=rf.predict(X_test)
# 画出样本的散点图
plt.scatter(X_test[:,0],X_test[:,1],c=y_pred_rf,s=20)
plt.title('Random forest classification result')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

在这里插入图片描述

4.3 LightGBM

  • LightGBM是微软开发的一款快速、分布式、高性能基于决策树的梯度提升框架,也就是GBDT算法工程实现,它主要有以下优势:
    • 训练效率快
    • 低内存使用
    • 准确率高
    • 支持并行学习
    • 可处理大规模数据
  • 运行以下指令安装lightgbm:
    • pip3 install lightgbm
  • 以下为常规需要设置的参数:
    • boosting_type:提升算法类型,默认gbdt 即传统GBDT算法,如果数据量较大,可以设置为’gross’,它会在牺牲一定精度的条件下加快模型的训练。
    • objective:指定学习任务,可选项有:
      • 对于LGBMRegressor(回归任务),选择’regression’;
      • 对于LGBMClassifier(分类任务),如果是二分类,选择‘binary’,如果是多分类,选择‘multiclass’;
      • 对于LGBMRanker(排序任务),选择‘lambdarank’。
import lightgbm as lgb
params={
    
    
	'boosting_type':'gbdt',
	'objective':'binary',
	'n_estimators':200,
	'learning_rate':0.1,
	'max_depth':5,
	'num_leaves':25,
	'min_child_samples':14,
	'subsample':0.8,
	'colsample_bytree':0.7,
	'subsample_freq':10,
	'reg_alpha':1.0,
	'reg_lambda':0.1,
}
model=lgb.LGBMClassifier(**params,random_state=50)
#训练模型
model.fit(X_train,y_train,eval_metric='auc',eval_set=[(X_test,y_test)],eval_names=['test'])
y_pred_lgb=model.predict(X_test)
y_pred_proba_lgb=model.predict_proba(X_test)
# 画出样本的散点图
plt.scatter(X_test[],X_test[],c=y_pred_lgb,s=20)
plt.title('LightGBM classification result')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

在这里插入图片描述

5.分类模型评价指标

所使用的评价指标包括:混淆矩阵 准确率
-\ 真阳率和假阳率\ROC\AUC\PR曲线\AP\F1 score

5.1 混淆矩阵

from sklearn.metrics import confusion_matrix
c_matric_dt=confusion_matrix(y_test,y_pred_dt)
c_matric_rf=confusion_matrix(y_test,y_pred_rf)
c_matric_lgb=confusion_matrix(y_test,y_pred_lgb)
print('Decison tree confusion_matrix:\n{}\n'.format(c_matric_dt))
print('Random Forest confusion_matrix:\n{}\n'.format(c_matric_rf))
print('LightGBM confusion_matrix:\n{}\n'.format(c_matric_lgb))
# print的输出结果
Decison tree confusion_matrix:
[[77  2]
 [ 3 68]]

Random Forest confusion_matrix:
[[79  0]
 [ 6 65]]

LightGBM confusion_matrix:
[[77  2]
 [ 3 68]]

5.2 准确率

from sklearn.metrics import accuracy_score
accuracy_dt=accuracy_score(y_test,y_pred_dt)
accuracy_rf=accuracy_score(y_test,y_pred_rf)
accuracy_lgb=accuracy_score(y_test,y_pred_lgb)
print('Decison tree accuracy:\n{}\n'.format(accuracy_dt))
print('Random Forest accuracy:\n{}\n'.format(accuracy_rf))
print('LightGBM accuracy:\n{}\n'.format(accuracy_lgb))
# print输出结果
Decison tree accuracy:
0.9666666666666667

Random Forest accuracy:
0.96

LightGBM accuracy:
0.9666666666666667

5.3 真阳率和假阳率

import pandas as pd
from sklearn.metrics import roc_curve
# 计算fpr和tpr
fpr,tpr,thresholds=roc_cure(y_test,y_pred_proba_lgb[:,1])
# 把fpr,tpr,thresholds用DataFrame表格保存,方便显示
result=pd.DataFrame([thresholds,tpr,fpr],index=['thresholds','tpr','fpr'])
print(result)
# print输出结果:
                  0         1         2         3         4         5   \
thresholds  1.992467  0.992467  0.943519  0.937773  0.813253  0.407940   
tpr         0.000000  0.887324  0.915493  0.929577  0.957746  0.957746   
fpr         0.000000  0.000000  0.012658  0.025316  0.025316  0.037975   

                  6         7         8         9        10  
thresholds  0.343985  0.185725  0.132040  0.044848  0.00497  
tpr         0.971831  0.985915  0.985915  0.985915  1.00000  
fpr         0.037975  0.075949  0.101266  0.227848  1.00000 

5.4 ROC

import matplotlib.pyplot as plt
plt.figure()
# 画出散点图,标出点的位置
plt.scatter(fpr,tpr)
# 画出ROC曲线图
plt.plot(fpr,tpr,color='darkorange',lw=2,label='ROC curve')
plt.xlim([-0.05,1.0])
plt.ylim([0.0,1.05])
plt.xlable('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('LightGBM ROC')
plt.legend(loc='lower right')
plt.show()

在这里插入图片描述

5.5 AUC

from sklearn.metrics import roc_auc_score
auc_dt=roc_auc_score(y_test,y_pred_dt)
auc_rf=roc_auc_score(y_test,y_pred_rf)
auc_lgb=roc_auc_score(y_test,y_pred_lgb)
print('Decision tree AUC:{:.3f}\n'.format(auc_dt))
print('Random Forest AUC:{:.3f}\n'.format(auc_rf))
print('LightGBM AUC:{:.3f}\n'.format(auc_lgb))
# print 输出结果
Decision tree AUC:0.966
Random Forest AUC:0.958
LightGBM AUC:0.966

5.6 精准率和召回率

from sklearn.metrcis import precision_recall_curve
# 计算precision和recall
precision,recall,thresholds=precision_recall_curve(y_test,y_pred_proba_lgb[:,1])
# 把precision,recall,thresholds用DataFrame表格保存,方便显示
result=pd.DataFrame([thresholds,precision,recall],index=['thresholds','precision','recall'])
print(result)
# print输出显示
                  0         1         2         3         4         5   \
thresholds  0.004970  0.044848  0.132040  0.185725  0.343985  0.407940   
precision   0.473333  0.795455  0.897436  0.921053  0.958333  0.957746   
recall      1.000000  0.985915  0.985915  0.985915  0.971831  0.957746   

                  6         7         8         9         10   11  
thresholds  0.813253  0.897236  0.937773  0.943519  0.992467  NaN  
precision   0.971429  0.971014  0.970588  0.984848  1.000000  1.0  
recall      0.957746  0.943662  0.929577  0.915493  0.887324  0.0

5.7 PR曲线

#规定画布大小
plt.figure(figsize=(12,8))
# 画填充图
plt.fill_between(recall,precision,alpha=0.2,color='b',step='post')
# 画散点图,凸显坐标点位置
plt.scatter(recall,precision,alpha=0.8,color='r')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0,1.05])
plt.xlim([0.0,1.05])
plt.show()

在这里插入图片描述

5.8 AP

from sklearn.metrics import average_precision_score
ap_dt=average_precision_score(y_test,y_pred_dt)
ap_rf=average_precision_score(y_test,y_pred_rf)
ap_glb=average_precision_score(y_test,y_pred_glb)
print('Decision tree AP:{:3f}\n'.formata(ap_dt))
print('Random Forest AP:{:3f}\n'.formata(ap_rf))
print('LightGBM AP:{:3f}\n'.formata(ap_glb))
# print 输出结果
Decision tree AP:0.950382
Random Forest AP:0.955493
LightGBM AP:0.950382

5.9 F1 score

from sklearn.metrics import f1_score
f1_score_dt=f1_score(y_test,y_pred_dt)
f1_score_rf=f1_score(y_test,y_pred_rf)
f1_score_lgb=f1_score(y_test,y_pred_lgb)
print('Decision tree f1_score:{:3f}\n'.format(f1_score_dt))
print('Random Forest f1_score:{:3f}\n'.format(f1_score_rf))
print('LightGBM f1_score:{:3f}\n'.format(f1_score_lgb))
# print 输出结果
Decision tree f1_score:0.964539
Random Forest f1_score:0.955882
LightGBM f1_score:0.964539

6.交叉验证

  • 问题思考:从整体数据中分离出一部分作为校验集会使模型能训练的数据减少,特别是数据量较少的情况下,有什么更好的办法能有效的利用数据集训练?
  • 答案:交叉验证
  • 交叉验证定义:
    • 交叉验证的思路其实就是重复利用数据,把得到的样本数据进行切分,组合为不同的训练集和测试集,训练集用于训练模型,测试集用于评估模型预测的好坏。
  • 何时使用交叉验证:
    • 交叉验证通常用在数据不太充足的时候,如果数据样本量小于一万,就需要采用交叉验证来评估模型,如果样本大于一万条的话,只要分出一部分数据作为校验集做模型评估即可。
    • 根据不同的数据切分方式,常用的交叉验证可以分为2中情况:
      • K折交叉验证
      • 留一交叉验证

6.1 K折交叉验证

  • 验证的过程也是工程量巨大,本篇文章会持续更新

猜你喜欢

转载自blog.csdn.net/weixin_42961082/article/details/113815145
今日推荐