Production-Ready ML Pipeline

Heart Disease
Detection System

Companion to the December 2025 paper on hybrid Deep Neural Network + XGBoost ensembles. The stack fuses BRFSS and HEART_2020 cohorts, semi-supervised pseudo-labeling, and recall-first threshold tuning to deliver reproducible cardiovascular risk prediction.

0 Hybrid AUC %
0 Recall %
0 F1 Score %
Heart Disease Detection visual board

Hybrid ML Heart Disease Paper (Dec 2025)

The published manuscript consolidates the complete scientific narrative: motivation, literature review, methodology, experiments, and deployment guidance for the hybrid DNN + XGBoost system.

Background & Motivation

Cardiovascular disease drives 17.9 million deaths globally each year, and U.S. prevalence hovers around one in five deaths. The paper frames this project as a recall-focused clinical decision support tool that improves on Framingham-style risk charts (AUC 0.73–0.76) by modelling nonlinear interactions.

Research Contributions

  • Hybrid ensemble (XGBoost + DNN + logistic stacker) reaching AUC 0.9458.
  • Cross-dataset feature alignment and semi-supervised pseudo-labeling.
  • Clinical threshold optimization targeting recall ≥ 0.90.
  • Optuna-driven hyperparameter search with reproducible pipeline.
  • Comprehensive statistical testing (bootstrap CI + DeLong).
  • Deployment checklist spanning governance, fairness, and monitoring.

Dataset Footprint

BRFSS 2020 provides >400K labeled survey rows; HEART_2020 contributes ~300K auxiliary rows. After harmonization and pseudo-label filtering, 80K confident examples extend the supervised signal without compromising quality (false pseudo-label rate <3%).

400K
BRFSS Samples
300K
HEART_2020 Rows
80K
Pseudo-Labels
0.3425
Chosen Threshold

Structure at a Glance

  • 1. Introduction
  • 2. Literature Review
  • 3. Methodology
  • 4. Implementation Details
  • 5. Experimental Results
  • 6. Discussion
  • 7. Conclusion & Future Work
  • Appendix A: XGBoost Tuning
  • Appendix B–D: DNN & Source Code
  • Appendix E–I: Compute, Deployment, Stats, Data, Glossary

From Data Harmonization to Threshold Tuning

Section 3 of the paper lays out the end-to-end process: aligned data sources, hybrid model architectures, pseudo-labeling, and a recall-constrained decision policy. The highlights below mirror that narrative.

3.1

Data Harmonization

Feature alignment maps BRFSS and HEART_2020 columns, followed by a ColumnTransformer that scales numeric signals and one-hot encodes categoricals before splitting into 70/15/15 train/val/test folds.

3.2

Hybrid Stack

XGBoost handles structured interactions, a 3-layer hourglass DNN captures nonlinear manifolds, and a logistic meta-learner fuses both validation logits. The stack yields +2.4% AUC over the best base model.

3.3

Pseudo-Labeling Strategy

Only confident predictions become labels: pos_thresh=0.97, neg_thresh=0.03. This expands the training corpus by 26.7% while keeping estimated noise <3%.

3.4

Threshold Optimization

A 37-point grid search enforces recall ≥0.90 on validation data and selects the highest-precision option, settling on t=0.3425 (test recall 0.9012, precision 0.7039).

4.x

Implementation & Compute

Optuna orchestrates hyperparameter trials, artifacts are versioned to artifacts/, and the full run takes ~15 minutes on a Xeon E5 + NVIDIA V100 workstation (Appendix E).

Model Metrics

All metrics are computed on a held-out test set and stored in artifacts/metrics.json. The hybrid model outperforms individual components.

🎯
0%
Hybrid AUC
hybrid_auc × 100
📊
0%
XGBoost AUC
xgb_auc × 100
🧠
0%
DNN AUC
dnn_auc × 100
✅
0%
Precision
test_precision
🔍
0%
Recall
test_recall
⚖️
0%
F1 Score
test_f1
🎚️
0
Decision Threshold
decision_threshold
📈
0%
Val Precision
val_precision

Training Workflow

The complete end-to-end pipeline from raw BRFSS data to production-ready model artifacts.

Training layout instructions visual
1

Data Ingestion

Load CDC BRFSS 2020 survey data containing 400k+ health indicator records with 18 features related to cardiovascular health.

2

Preprocessing

Run brfss_preprocessing.py to handle missing values, encode categoricals, normalize numerics, and align feature schemas.

3

Feature Engineering

Execute prune_features.py for feature selection using importance scores and correlation analysis to reduce noise.

4

Hybrid Training

Train DNN for representation learning, then feed embeddings to XGBoost. Optuna tunes both model families for optimal performance.

5

Evaluation & Export

Compute metrics, generate publication plots via sham_plots.py, and export artifacts to artifacts/ directory.

Model Flow Diagram

Understanding how data flows through the hybrid DNN-XGBoost architecture from input to prediction.

Model flow visual selection board
📥

Input Layer

Raw features from BRFSS dataset including demographics (age, sex), lifestyle factors (smoking, alcohol), and medical history (diabetes, stroke, kidney disease).

🧠

DNN Feature Extractor

Multi-layer neural network with batch normalization and dropout. Learns non-linear representations and extracts high-level features from tabular data.

🌲

XGBoost Classifier

Gradient boosting ensemble receives both original features and DNN embeddings. Handles feature interactions and provides robust classification.

⚡

Hybrid Fusion

Combines DNN probability outputs with XGBoost predictions using weighted averaging. Threshold optimization via recall-constrained precision sweep.

📤

Risk Prediction

Final binary classification (Heart Disease: Yes/No) with calibrated probability scores. Decision threshold set at 0.3425 for optimal recall-precision balance.

Visual Storytelling

High-resolution hero graphics generated in assets/ showcase the hybrid pipeline and workflow narrative.

Hybrid pipeline visual board
Visual selection board (assets/_- visual selection.png) now powers the hero and architecture sections, illustrating the hybrid DNN + XGBoost story.
Layout instructions graphic
Layout instruction sheet (assets/📌 Exact Layout Instructions_ - visual selection.png) highlights the training workflow narrative and supports the pipeline section.

Algorithm Deep Dive

Key excerpts from hybrid_dnn_xgb.py highlighting how stacked learners and recall-constrained thresholding work together.

Hybrid Stack Training train_base_models_and_meta · lines 150-210

Trains XGBoost and DNN separately, then feeds their validation probabilities to a logistic meta-learner that delivers the hybrid AUC lift.

def train_base_models_and_meta(X_train, y_train, X_val, y_val):
    pos_ratio = y_train.mean()
    scale_pos_weight = (1 - pos_ratio) / max(pos_ratio, 1e-6)

    xgb_model = build_xgb_model(scale_pos_weight)
    xgb_model.fit(X_train, y_train)
    xgb_val = xgb_model.predict_proba(X_val)[:, 1]

    dnn_model = build_dnn_model(X_train.shape[1])
    dnn_model.fit(X_train, y_train, validation_data=(X_val, y_val),
                  epochs=DNN_EPOCHS, batch_size=DNN_BATCH_SIZE,
                  callbacks=[early_stop])
    dnn_val = dnn_model.predict(X_val, batch_size=DNN_BATCH_SIZE).ravel()

    meta_X = np.vstack([xgb_val, dnn_val]).T
    meta_model = LogisticRegression(...).fit(meta_X, y_val)
    hybrid_val_auc = roc_auc_score(y_val, meta_model.predict_proba(meta_X)[:, 1])
Recall-Constrained Threshold tune_threshold_for_recall_precision · lines 250-300

Sweeps decision thresholds to guarantee ≥90% recall on validation, then locks in the option with the strongest precision, falling back to F1 if needed.

def tune_threshold_for_recall_precision(y_true, y_proba, min_recall=0.90):
    best_thresh = 0.5
    best_prec = best_rec = best_f1 = -1
    chosen_by = "f1_fallback"
    fallback_t = 0.5
    fallback_prec = fallback_rec = 0.0
    fallback_f1 = -1

    for t in THRESH_GRID:
        y_pred = (y_proba >= t).astype(int)
        prec = precision_score(y_true, y_pred, zero_division=0)
        rec = recall_score(y_true, y_pred, zero_division=0)
        f1 = f1_score(y_true, y_pred, zero_division=0)

        if rec >= min_recall and prec > best_prec:
            best_thresh = float(t)
            best_prec, best_rec, best_f1 = prec, rec, f1
            chosen_by = "recall_constrained_precision"

        if f1 > fallback_f1:
            fallback_t, fallback_prec = float(t), prec
            fallback_rec, fallback_f1 = rec, f1

    if chosen_by == "f1_fallback":
        best_thresh = fallback_t
        best_prec, best_rec, best_f1 = fallback_prec, fallback_rec, fallback_f1

    return best_thresh, {
        "val_precision": float(best_prec),
        "val_recall": float(best_rec),
        "threshold_source": chosen_by,
    }

Performance Highlights from Section 5

Statistical comparisons, pseudo-label ablations, and clinical threshold analyses from the paper feed directly into the dashboard below.

Hybrid vs Baselines

0.9458 AUC

Stacked model improves on XGBoost (0.9215) and DNN (0.9093) courtesy of the logistic meta-learner.

Clinical Recall

90.12%

Operating at t=0.3425 maintains cardiology-grade sensitivity while precision holds at 70.39%.

Pseudo-Label Lift

+0.7% ΔAUC

Adding 80K confident pseudo-labels increases validation AUC without measurable drift (noise <3%).

Training Timeline

~15 min

Data ingest 30s, XGBoost 120s, DNN 480s, pseudo-labeling 60s, threshold sweep 30s on V100-class hardware.

Bootstrap confidence intervals (1,000 stratified iterations) and DeLong tests confirm the hybrid model’s lift over single learners at α = 0.05. Section 5.3 and Appendix G provide derivations plus the reference implementations.

Evaluation Charts

Publication-ready plots generated by artifacts/sham_plots.py for research papers and presentations.

ROC Comparison

ROC Curve Comparison Discrimination

Receiver Operating Characteristic curves for all three models. The hybrid ensemble (green) achieves the highest AUC by leveraging complementary strengths of DNN feature learning and XGBoost's gradient boosting. The diagonal represents random guessing (AUC = 0.5).

0.9458 Hybrid AUC
0.9215 XGBoost AUC
0.9093 DNN AUC
Accuracy Comparison

Accuracy vs Threshold Calibration

Shows how classification accuracy varies across decision thresholds. Each model has an optimal operating point. The hybrid model maintains stable high accuracy across a wider threshold range, indicating better probability calibration.

0.3425 Optimal Threshold
Recall Comparison

Recall vs Threshold Sensitivity

Critical for medical applications where missing positive cases (heart disease) is costly. The threshold was specifically chosen to maintain 90%+ recall while maximizing precision. Lower thresholds catch more positives but increase false alarms.

90.12% Test Recall
Metrics Bar Chart

Metrics Comparison Overview

Side-by-side comparison of precision, recall, and F1 scores across all models. The hybrid approach consistently outperforms or matches the best individual model on each metric, demonstrating effective ensemble learning.

79.10% Hybrid F1
Hybrid Final Comparison

Hybrid vs Baseline Final

Direct comparison between the hybrid ensemble and the strongest single model (XGBoost). Bars show improvements across accuracy, precision, recall, F1, and AUC. The hybrid model achieves gains on all five headline metrics.

AUC Bar Chart

AUC Score Breakdown Ranking

Bar chart ranking each model by Area Under ROC Curve. AUC measures the model's ability to distinguish between positive and negative classes across all thresholds. Higher is better, with 1.0 representing perfect discrimination.

AUC Lollipop Chart

AUC Lift Analysis Improvement

Lollipop chart emphasizing the incremental AUC gains from the hybrid approach. The visualization highlights how combining DNN and XGBoost yields a 2-3% AUC improvement over either individual model—significant in medical ML applications.

Summary Grid

Complete Summary Grid Dashboard

All-in-one visualization combining ROC curves, accuracy sweeps, and key metrics in a single figure. Designed for academic papers and presentations where space is limited but comprehensive model comparison is needed.

Checklist from Appendix F

The paper treats clinical deployment as a first-class concern. These cards summarize the governance, infrastructure, and monitoring requirements before the model can enter a hospital workflow.

Pre-Deployment Validation

  • External validation on independent health system cohorts.
  • Fairness audits across demographics plus calibration plots.
  • Sensitivity analyses on hyperparameters and decision threshold.

Clinical Governance

  • Institutional Review Board approvals and consent pathways.
  • Clinician enablement: workflow design, training, documentation.
  • Patient communication materials describing model use.

Technical Infrastructure

  • Artifact versioning, API wrapper, and EHR integration tests.
  • Performance dashboards, incident response, audit logging.
  • Inference latency budgets (100 ms single sample, 25 ms batch).

Post-Deployment Monitoring

  • Monthly KPI review (AUC, recall, precision) with drift detection.
  • Quarterly fairness audits and user feedback loops.
  • Scheduled continuous retraining with updated BRFSS-style surveys.

Technology Stack

Production-grade tools and frameworks powering the pipeline.

🧠
TensorFlow
DNN Training
🌲
XGBoost
Gradient Boosting
🎯
Optuna
Hyperparameter Tuning
🐼
Pandas
Data Processing
📊
Matplotlib
Visualization
🔬
Scikit-learn
Preprocessing
🔢
NumPy
Numerical Ops
💡
SHAP
Explainability

Quick Start Guide

Clone, install, and run the complete pipeline in minutes.

1
Clone Repository
git clone https://github.com/chirag-gupta7/Heart-disease-detection.git
cd Heart-disease-detection
2
Install Dependencies
pip install -r requirements.txt
# Includes TensorFlow, XGBoost, Optuna, Pandas, etc.
3
Preprocess Data
python brfss_preprocessing.py
# Outputs: brfss2020_aligned.csv
4
Train Hybrid Model
python hybrid_dnn_xgb.py
# Outputs: artifacts/metrics.json + plots
5
Generate Visualizations
python artifacts/sham_plots.py
# Outputs: artifacts/plots_lightweight/*.png