在使用机器学习进行冠心病(CAD)预测时,绘制ROC曲线、DCA曲线和校准曲线可以帮助评估模型的性能。这些评估方法可以揭示模型的分类能力、临床效益以及预测概率的准确性。以下是进行冠心病预测并绘制这些曲线的步骤和评价指标:
1. 数据准备
首先,确保你的数据已经处理好,包括特征工程和数据预处理。假设数据包含以下字段:
- 特征: 例如年龄、性别、血压、胆固醇水平等。
- 目标: 是否患有冠心病(0 表示无,1 表示有)。
2. 训练模型
使用适合的机器学习模型进行训练,例如逻辑回归、随机森林、XGBoost等。
数据:
import pandas as pd
from sklearn.model_selection import train_test_split
# 假设数据已经加载到DataFrame中
data =df = pd.read_csv('冠心病10年数据修改版_1.csv')
# 特征和目标
X = data.drop('OS', axis=1)
y = data['OS']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
import xgboost as xgb
# 创建XGBoost模型
model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss')
# 训练模型
model.fit(X_train, y_train)
from sklearn.metrics import roc_curve, auc, precision_recall_curve, roc_auc_score, brier_score_loss
import matplotlib.pyplot as plt
import numpy as np
from sklearn.calibration import calibration_curve
# 预测概率
y_prob = model.predict_proba(X_test)[:, 1]
# ROC曲线
fpr, tpr, _ = roc_curve(y_test, y_prob)
roc_auc = auc(fpr, tpr)
# DCA曲线 (以0.1的阈值为例)
def dca_curve(y_true, y_prob, thresholds=[0.1, 0.2, 0.3, 0.4, 0.5]):
dca_results = []
for threshold in thresholds:
y_pred = (y_prob >= threshold).astype(int)
tp = np.sum((y_pred == 1) & (y_true == 1))
fp = np.sum((y_pred == 1) & (y_true == 0))
tn = np.sum((y_pred == 0) & (y_true == 0))
fn = np.sum((y_pred == 0) & (y_true == 1))
net_benefit = (tp - fp * (threshold / (1 - threshold))) / len(y_true)
dca_results.append(net_benefit)
return dca_results
thresholds = np.linspace(0, 1, 10)
dca_results = dca_curve(y_test, y_prob, thresholds)
# 校准曲线
prob_true, prob_pred = calibration_curve(y_test, y_prob, n_bins=10, strategy='uniform')
# 绘制曲线
plt.figure(figsize=(15, 5))
# ROC曲线
plt.subplot(1, 3, 1)
plt.plot(fpr, tpr, color='blue', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='grey', linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.legend(loc='lower right')
# DCA曲线
plt.subplot(1, 3, 2)
plt.plot(thresholds, dca_results, marker='o')
plt.xlabel('Threshold')
plt.ylabel('Net Benefit')
plt.title('DCA Curve')
# 校准曲线
plt.subplot(1, 3, 3)
plt.plot(prob_pred, prob_true, marker='o', label='Calibration curve')
plt.plot([0, 1], [0, 1], color='grey', linestyle='--')
plt.xlabel('Mean Predicted Probability')
plt.ylabel('Fraction of Positives')
plt.title('Calibration Curve')
plt.tight_layout()
plt.show()