基于机器学习的心脏病预测方法(11)——梯度提升机(GBM)
梯度提升机(GBM)是一种集成学习算法,基于Boosting方法,通过串行训练多个弱学习器来逐步优化模型。它通过拟合损失函数的负梯度并使用加法模型提升性能,常用于分类和回归任务。常用基学习器为决策树,具体实现包括XgBoost、LightGBM和CatBoost。该方法在医疗数据分析中表现优异,准确率高达80.33%。通过混淆矩阵、精确率、召回率、F分数、FN值、ROC曲线和AUC指标等多方面评估,模型在诊断任务中表现出良好的性能,AUC值为0.915,表明其分类能力较强。
目录
一
3.1
一
二
三
3.1
一、梯度提升机介绍
GBM(Gradient Boosting Algorithm)算法是一种基于梯度的提升算法。其核心思想是通过依次生成多个弱学习器,每个弱学习器的目标是估计并纠正前一个累加模型对损失函数的负梯度方向的拟合,从而逐步降低整体模型的损失值。此外,该算法通过不同权重对基学习器进行线性集成,以充分利用表现优异的个体模型。需要注意的是,GBM属于加法模型,其全称是Multiplicative Additive Regression Trees( MART)。
主流的基学习器多为树模型,基于决策树的技术发展而来的算法被称为GBDT(Gradient Boosting Decision Tree)。这些工具如XgBoost、LightGBM、CatBoost等,均基于GBDT(采用CART树)的技术发展而来。
GBM梯度推进方法(或推进式提升方法)是一种集成学习模型(Ensemble)。GBM(Gradient Boosting Machine)方法属于提升方法(Boosting)范畴。GBM的核心理念是通过基于损失函数的梯度下降方向逐步构建新的基学习器,最终通过集成多个基学习器使模型的损失函数逐步降低,从而实现模型的持续优化。
二、核心代码
首先需要导入相应库和数据集:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
data = pd.read_csv('heart.csv', sep=',')
data.head()
运行结果:

然后划分训练集和测试集(训练集80%,测试集20%):
from sklearn.model_selection import train_test_split
predictors = data.drop("target",axis=1)
target = data["target"]
X_train,X_test,Y_train,Y_test = train_test_split(predictors,target,test_size=0.20,random_state=0)
print("Training features have {0} records and Testing features have {1} records.".\
format(X_train.shape[0], X_test.shape[0]))
Training features correspond to 242 records, and also, Testing features consist of 61 records.

逻辑回归核心代码如下:
from sklearn.ensemble import GradientBoostingClassifier
gbc =GradientBoostingClassifier()
gbc.fit(X_train, Y_train)
y_pred_gbc = gbc.predict(X_test)
准确率:
from sklearn.metrics import accuracy_score
score_gbc = round(accuracy_score(y_pred_gbc,Y_test)*100,2)
print("GBM算法的准确率是: "+str(score_gbc)+" %")
运行结果:
GBM算法的准确率是: 80.33 %
查看各个指标的重要性:
n_features = X_train.shape[1]
plt.barh(range(n_features), gbc.feature_importances_, align='center')
plt.yticks(np.arange(n_features), X_train.columns)
plt.xlabel("Feature importance")
plt.ylabel("Feature")
plt.ylim(-1, n_features)
plt.show()
运行结果:

三、评价指标
3.1 混淆矩阵
from sklearn.metrics import confusion_matrix
matrix= confusion_matrix(Y_test, y_pred_gbc)
sns.heatmap(matrix,annot = True, fmt = "d")
运行结果:

3.2 预测分数
from sklearn.metrics import precision_score
precision = precision_score(Y_test, y_pred_gbc)
print("Precision: ",precision)
运行结果:
Precision: 0.8235294117647058
3.3 召回率
from sklearn.metrics import recall_score
recall = recall_score(Y_test, y_pred_gbc)
print("Recall is: ",recall)
运行结果:
Recall is: 0.8235294117647058
3.4 F分数
print((2*precision*recall)/(precision+recall))
运行结果:
0.8235294117647058
3.5 FN(false negative)
CM = pd.crosstab(Y_test, y_pred_gbc)
TN=CM.iloc[0,0]
FP=CM.iloc[0,1]
FN=CM.iloc[1,0]
TP=CM.iloc[1,1]
fnr = FN*100/(FN+TP)
fnr
运行结果:
17.647058823529413
3.6 ROC曲线
from sklearn.metrics import roc_curve, auc
y_pred=gbc.predict(X_test)
y_proba=gbc.predict_proba(X_test)
fpr, tpr, thresholds = roc_curve(Y_test, y_proba[:,1])
fig, ax = plt.subplots()
ax.plot(fpr, tpr)
ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls="--", c=".3")
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.rcParams['font.size'] = 12
plt.title('ROC curve for diabetes classifier')
plt.xlabel('False Positive Rate (1 - Specificity)')
plt.ylabel('True Positive Rate (Sensitivity)')
plt.grid(True)
运行结果:
略
3.7 AUC指标
auc(fpr, tpr)
运行结果:
0.915032679738562
