Heart Disease Prediction Using Machine Learning: Guide & Project
A heart disease prediction model is not a medical device. It is a classification exercise on a small dataset that teaches you how to build responsibly when the stakes are higher than a Kaggle leaderboard. The difference between a student project that impresses and one that embarrasses is not the algorithm you choose. It is whether you understand that a false negative (telling a sick patient they are healthy) is worse than a false positive (telling a healthy patient to get a checkup), and whether you build and evaluate your model accordingly.
This guide walks through the complete project on the standard UCI Heart Disease dataset: the data explained in plain language, the exploratory analysis that surfaces real risk patterns, three models compared on the metric that matters in medicine (recall, not accuracy), threshold tuning that accepts more false alarms to miss fewer patients, and the limitations section that makes your write-up defensible in a viva or interview.
Cardiovascular diseases are the leading cause of death globally, accounting for an estimated 17.9 million deaths per year according to the World Health Organization. Early detection saves lives. Machine learning models trained on clinical features can assist screening, but they are tools for prioritization, not replacements for clinical judgment.
The AI in healthcare guide covers where ML fits in the broader medical technology landscape.
The UCI Dataset: 13 Features in Plain Language
The standard dataset for this project is the Cleveland Heart Disease Dataset from the UCI Machine Learning Repository. It was collected by Robert Detrano, M.D., Ph.D., at the VA Medical Center in Long Beach and the Cleveland Clinic Foundation.
Dataset facts:
| Attribute | Value |
|---|---|
| Total samples | 303 |
| Features | 13 |
| Target | Presence of heart disease (0 = no, 1 = yes) |
| Class balance | Approximately 54% disease, 46% no disease |
The 303-sample Cleveland subset is the most commonly used version. The full UCI collection includes data from four institutions (Cleveland, Hungary, Switzerland, and Long Beach VA) totaling approximately 920 samples, but the Cleveland subset is the standard benchmark because it is the most complete.
The 13 Features Explained
| Feature | Meaning | Values |
|---|---|---|
| age | Patient age in years | 29 to 77 |
| sex | Biological sex | 1 = male, 0 = female |
| cp | Chest pain type | 1 = typical angina, 2 = atypical angina, 3 = non-anginal pain, 4 = asymptomatic |
| trestbps | Resting blood pressure (mm Hg) | 94 to 200 |
| chol | Serum cholesterol (mg/dl) | 126 to 564 |
| fbs | Fasting blood sugar > 120 mg/dl | 1 = true, 0 = false |
| restecg | Resting electrocardiographic results | 0 = normal, 1 = ST-T abnormality, 2 = LV hypertrophy |
| thalach | Maximum heart rate achieved | 71 to 202 |
| exang | Exercise-induced angina | 1 = yes, 0 = no |
| oldpeak | ST depression induced by exercise | 0.0 to 6.2 |
| slope | Slope of peak exercise ST segment | 1 = upsloping, 2 = flat, 3 = downsloping |
| ca | Number of major vessels colored by fluoroscopy | 0 to 3 |
| thal | Thalassemia | 3 = normal, 6 = fixed defect, 7 = reversible defect |
Several of these features require clinical context to interpret correctly. Chest pain type 4 (asymptomatic) is paradoxically the highest-risk category because asymptomatic heart disease is often detected only through screening. The thalach feature (maximum heart rate) being lower in disease patients reflects reduced cardiac output capacity, not fitness.
EDA: What the Data Actually Shows
Before training any model, the exploratory analysis should surface which features carry genuine signal. Here are the patterns that matter:
Build an AI-First Career, Master the Complete Skillset
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
AI Forward Deployed Engineer Program
Full-stack engineering, production AI and client-facing consulting
+1000 moreKey EDA Findings
Age distribution by disease status: Patients with heart disease skew older (median age approximately 58 vs 52 for healthy patients), but the overlap is substantial. Age alone is not diagnostic.
Chest pain type is the strongest single feature: Type 4 (asymptomatic) appears in approximately 60 percent of disease patients but only 10 percent of healthy patients. This single feature carries more discriminative power than any other.
Maximum heart rate (thalach) is inversely correlated with disease: Disease patients achieve lower maximum heart rates during exercise testing (median approximately 140 vs 160 for healthy patients). This reflects reduced cardiac reserve.
ST depression (oldpeak) is higher in disease patients: Exercise-induced ST depression indicates myocardial ischemia. Disease patients show median oldpeak of approximately 1.5 vs 0.5 for healthy patients.
Correlation heatmap: The strongest correlations with the target are chest pain type (approximately 0.43), thalach (approximately -0.42), oldpeak (approximately 0.43), and number of colored vessels (approximately 0.47). Cholesterol and fasting blood sugar show surprisingly weak correlations, which is worth noting because students often assume these would dominate.
Sharpen your EDA skills before building: Scaler's free Python for Data Science course covers pandas, visualization, and statistical exploration with structured exercises.
Stop learning AI in fragments—master a structured AI Engineering Course with hands-on GenAI systems with IIT Roorkee CEC Certification
:::
Three Models, Judged Recall-First
In medical screening, the primary metric is recall (also called sensitivity): what percentage of actual patients does the model correctly identify? A model that catches 90 percent of patients but generates more false alarms is preferable to one that catches only 70 percent but generates fewer false alarms. The missed patient is the expensive error.
Here is the model comparison framework:
Results
| Model | Accuracy | CV Recall | Precision | F1 |
|---|---|---|---|---|
| Logistic Regression | 0.82 to 0.85 | 0.85 to 0.90 | 0.78 to 0.82 | 0.82 to 0.86 |
| KNN (k=5) | 0.78 to 0.82 | 0.80 to 0.85 | 0.75 to 0.80 | 0.78 to 0.82 |
| Random Forest | 0.80 to 0.85 | 0.82 to 0.88 | 0.77 to 0.82 | 0.80 to 0.85 |
What these numbers mean: All three models land in the 80 to 88 percent accuracy range, which is realistic for this dataset. Tutorial claims of 95+ percent accuracy on this 303-sample dataset usually indicate data leakage (scaling before splitting, or evaluating on training data). Logistic Regression tends to lead on recall because it is the most stable model on small datasets and produces well-calibrated probabilities.
The Logistic Regression guide covers why it performs well as a baseline, and the KNN guide explains the distance-based approach. For a comparison of all classification algorithms available for this type of problem, the classification algorithms guide maps when each algorithm is the right choice.
Threshold Tuning: The Medical Cost Asymmetry
By default, classifiers use a 0.5 probability threshold. A patient with a predicted probability of 0.51 gets flagged as "disease." In medical screening, this threshold is often too high. Lowering it catches more patients at the cost of more false alarms.
from sklearn.metrics import precision_recall_curve
Typical result: Lowering the threshold from 0.50 to approximately 0.35 to 0.40 increases recall from approximately 0.85 to approximately 0.92 while reducing precision from approximately 0.80 to approximately 0.72. This means you catch 92 percent of actual patients instead of 85 percent, but you also flag more healthy patients for unnecessary follow-up. In a medical screening context, this trade-off is acceptable because:
- A false positive costs a follow-up appointment (inconvenience, anxiety, approximately 500 per additional test)
- A false negative costs delayed diagnosis, disease progression, and potentially a life
The evaluation metrics guide covers the full framework for choosing metrics based on the cost structure of your problem.
Feature Importance (Read With Care)
Random Forest provides feature importance scores, and Logistic Regression provides coefficients. Both are useful but neither establishes causation.
Typical importance ranking:
| Feature | Approximate Importance |
|---|---|
| cp (chest pain type) | 0.14 to 0.18 |
| thalach (max heart rate) | 0.12 to 0.15 |
| ca (colored vessels) | 0.11 to 0.14 |
| oldpeak (ST depression) | 0.10 to 0.13 |
| age | 0.08 to 0.10 |
| slope | 0.06 to 0.09 |
| exang (exercise angina) | 0.05 to 0.08 |
| sex | 0.04 to 0.07 |
| thal | 0.04 to 0.06 |
| trestbps | 0.03 to 0.05 |
| chol | 0.03 to 0.05 |
| restecg | 0.02 to 0.04 |
| fbs (fasting blood sugar) | 0.01 to 0.03 |
What this tells you: Chest pain type, maximum heart rate, and number of colored vessels are the strongest predictors. This aligns with clinical knowledge: chest pain characteristics, exercise capacity, and angiographic findings are established indicators of coronary artery disease.
What this does not tell you: That these features cause heart disease. Feature importance reflects correlation in this specific dataset. A patient with high cholesterol and normal chest pain may still have heart disease that this model misses because cholesterol scored low on importance. The model captures statistical associations, not medical mechanisms.
The Demo: A Streamlit Interface
A working demo transforms this from a notebook exercise into something you can show in an interview or viva. Streamlit makes this straightforward:
import streamlit as st
import numpy as np
import joblib
st.title("Heart Disease Risk Assessment")
st.markdown("**DISCLAIMER:** This is a course project, not a medical diagnostic tool. Consult a healthcare professional for medical decisions.")
The disclaimer banner at the top is not optional. It is a required element of any healthcare ML project that demonstrates you understand the boundary between a course exercise and a clinical tool.
How Scaler Transformed Careers in Different Fields
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.
Limits, Ethics, and the Write-Up
The Limitations You Must State
Small dataset: 303 samples is far too few for a clinically reliable model. Published clinical prediction tools use thousands to tens of thousands of patient records. This dataset is adequate for learning ML methodology but not for medical deployment.
Population bias: The Cleveland dataset was collected from patients who were already referred for cardiac evaluation. It does not represent the general population. A model trained on referred patients will overestimate risk in a screening context.
Temporal bias: The data was collected in the late 1970s and early 1980s. Treatment protocols, diagnostic criteria, and population health characteristics have changed significantly since then.
Feature limitations: 13 features capture only a fraction of the clinical picture. Modern cardiac risk assessment includes family history, genetic markers, lifestyle factors, medication history, and imaging results that are not in this dataset.
Report Structure
A strong project report follows this structure:
- Problem framing: Why early detection matters, the recall-first evaluation rationale, the disclaimer
- Dataset description: Source, features explained, class balance, known biases
- EDA findings: Risk patterns with visualizations, correlation analysis
- Methodology: Train-test split, scaling, model selection, cross-validation
- Results: Model comparison table with accuracy and recall, threshold tuning analysis
- Feature analysis: Importance ranking with the correlation-not-causation caveat
- Demo: Streamlit interface screenshot with the disclaimer
- Limitations and ethics: All four limitations above, plus deployment ethics
- Conclusion: What the project demonstrates and what it does not
Viva Question Bank
"Why is recall more important than accuracy?" A false negative means a patient with heart disease is told they are healthy and does not seek treatment. A false positive means a healthy patient gets an additional checkup. The cost asymmetry between these two errors means that sensitivity (recall) is the primary metric. A model that catches 90 percent of patients with some false alarms is clinically preferable to one that catches 75 percent with fewer false alarms.
"Why not 95 percent accuracy?"
Claims above 88 to 90 percent on this 303-sample dataset usually indicate data leakage: scaling before splitting (the scaler sees test data), evaluating on training data, or oversampling before splitting. Honest evaluation on a proper held-out test set gives 80 to 88 percent accuracy, which is the realistic range.
"Can this model replace a doctor?"
No. It is a screening prioritization tool trained on 303 patients from a single clinic in the 1980s. Real clinical decision support requires regulatory approval, prospective validation on diverse populations, integration with electronic health records, and physician oversight. This project demonstrates ML methodology, not medical readiness.
"What would you improve?"
Larger and more diverse datasets, temporal validation (test on patients from a later time period), additional clinical features (family history, genetic markers), and prospective validation where the model's predictions are compared against actual clinical outcomes over time.
Healthcare ML demands rigor.
From imbalanced evaluation to medical ethics to production deployment, building ML systems that affect human health is the highest-responsibility work in the field. Scaler's AI and ML Program covers the full stack of applied ML with mentor-led guidance and industry-relevant projects.
Turn Learning into Career Growth
FAQs
Which algorithm is best for heart disease prediction?
On the UCI Cleveland dataset, Logistic Regression and Random Forest both reach approximately 80 to 88 percent accuracy. However, in a medical framing, the algorithm choice matters less than the evaluation metric. All three standard algorithms (Logistic Regression, KNN, and Random Forest) perform similarly on this dataset. The differentiator is tuning the decision threshold to maximize recall (catching actual patients) while maintaining acceptable precision, which is a modeling decision that applies regardless of which algorithm you choose.
What dataset is used for heart disease prediction projects?
The UCI Heart Disease Dataset (Cleveland subset) contains 303 patient records with 13 clinical features including age, sex, chest pain type, cholesterol, maximum heart rate, and exercise-induced ST depression. The target variable indicates the presence or absence of heart disease. It was collected at the Cleveland Clinic Foundation and is the standard benchmark for this project type. The dataset is freely available from the UCI Machine Learning Repository.
What accuracy is realistic for a heart disease prediction model?
Approximately 80 to 88 percent accuracy on a properly held-out test set, with recall in the 82 to 90 percent range when threshold-tuned. Tutorial claims of 95 percent or higher on this 303-sample dataset usually indicate data leakage from scaling before splitting, evaluating on training data, or oversampling before the train-test split. Stating realistic numbers honestly in your report demonstrates methodological maturity and strengthens your project's credibility.
Why is recall more important than accuracy for disease prediction?
A false negative (telling a patient with heart disease they are healthy) means delayed treatment and potential disease progression. A false positive (telling a healthy patient they might have heart disease) means an unnecessary follow-up appointment. The cost of missing a patient is dramatically higher than the cost of an extra checkup, which makes sensitivity or recall the primary metric. Threshold tuning should prioritize catching more patients even at the cost of more false alarms.
Is heart disease prediction a good final-year project?
It is one of the strongest project choices because it combines a clean classification problem with meaningful real-world context, requires responsible evaluation (recall over accuracy, threshold tuning), and demands an ethics and limitations discussion that elevates the project above purely technical exercises. Executed with the recall-first evaluation and the honest limitations section, it stands significantly apart from projects that treat a medical dataset like a generic benchmark.
Can a machine learning model actually diagnose heart disease?
Not at the course-project scale. The UCI dataset has 303 samples from a single population collected in the late 1970s, which is insufficient for clinical deployment. Real clinical decision support tools require tens of thousands of patient records, prospective validation across diverse populations, regulatory approval, and integration with clinical workflows. This project demonstrates ML methodology and responsible evaluation practices, not medical diagnostic capability.
