# 模型评估可视化 --------------------------------------------------------------
# 设置图形排版参数
par(mfrow = c(2, 2), mar = c(4.5, 4.5, 3, 2), cex.lab = 1.2, cex.main = 1.4)
### 1. ROC曲线分析 ---------------------------------------------------------
roc_obj <- roc(test_data$Hearing_loss, predictions$xgb)
# 绘制增强版ROC曲线
plot(roc_obj,
main = "ROC Curve (XGBoost)",
col = "#1F77B4",
lwd = 3,
legacy.axes = TRUE,
print.auc = TRUE,
auc.polygon = TRUE,
auc.polygon.col = "#FEE08B88",
grid = TRUE,
grid.col = "gray90",
xlab = "False Positive Rate",
ylab = "True Positive Rate")
### 2. 校准曲线 ------------------------------------------------------------
# 使用rms包绘制高级校准曲线
cal <- val.prob(predictions$xgb,
as.numeric(test_data$Hearing_loss)-1,
smooth = "loess",
logistic.cal = TRUE)
# 自定义绘图参数
plot(cal,
main = "Calibration Curve",
cex = 0.8,
col.ideal = "#D53E4F",
lwd.ideal = 2,
lty.ideal = 2,
col.smooth = "#3288BD",
lwd.smooth = 3,
riskdist = FALSE,
cex.lab = 1.2,
cex.axis = 1.1)
### 3. 决策曲线分析 --------------------------------------------------------
# 将预测概率添加到测试数据
test_data$pred_prob <- predictions$xgb
# 构建决策曲线对象
dca <- decision_curve(
Hearing_loss ~ pred_prob,
data = test_data,
thresholds = seq(0, 1, by = 0.05),
bootstraps = 50
)
# 绘制专业决策曲线
plot_decision_curve(dca,
main = "Decision Curve Analysis",
curve.names = "XGBoost Model",
col = "#5E4FA2",
lwd = 2,
confidence.intervals = FALSE,
standardize = TRUE,
cost.benefit.axis = FALSE,
xlab = "Threshold Probability",
ylab = "Net Benefit")
### 4. SHAP可视化 ----------------------------------------------------------
# 创建shapviz对象
shap_values <- shapviz(xgb_model,
X = model.matrix(~ . -1, test_data[, -which(names(test_data) == "Hearing_loss")]))
# 特征重要性图
sv_importance(shap_values,
max_display = 15,
fill_color = "#66C2A5",
show_numbers = TRUE) +
ggtitle("Feature Importance (SHAP Values)") +
theme(plot.title = element_text(face = "bold", size = 14))
# 瀑布图示例(显示第一个样本)
sv_waterfall(shap_values,
row_id = 1,
fill_colors = c("#F46D43", "#66C2A5")) +
ggtitle("Individual SHAP Explanation") +
theme(plot.title = element_text(face = "bold", size = 14))
# 重置图形参数
par(mfrow = c(1, 1))
# 保存所有图形 ------------------------------------------------------------
# PDF格式保存(矢量图)
pdf(paste0(output_path, "XGBoost_Evaluation.pdf"), width = 12, height = 10)
# 依次重新绘制各图形
plot(roc_obj) # ROC曲线
plot(cal) # 校准曲线
plot(dca) # 决策曲线
sv_importance(shap_values) # SHAP重要性
sv_waterfall(shap_values) # 瀑布图
dev.off()
# PNG格式保存(高分辨率)
ggsave(paste0(output_path, "SHAP_Importance.png"),
plot = sv_importance(shap_values),
width = 10, height = 8, dpi = 300)根据这个代码绘制训练集ROC曲线