3 numbers changed my risk score. Guess which.
Cholesterol? Blood pressure? Exercise? I built a heart disease prediction machine learning model, fed it one made-up patient, and asked a question most health apps never answer: not “what is my risk”, but “what is driving my risk, and what would actually move it?” The answer was 86.0%. Then three changes took it to 56.5%. One of the three did almost nothing on its own, and that turned out to be the most interesting part.
Educational demo only. This is not medical advice, not a diagnosis, and not a screening tool. This project cannot tell you whether you have heart disease, and you should never use it to make health decisions. If you are worried about your heart, see a doctor. Every number in this article comes from a 500-row built-in sample dataset, not from the full UCI Heart Disease dataset and not from real patients.

Why one number never tells the story
Ask someone their cholesterol and they will quote it like a football score. 290. Bad. End of story. Except a heart is not a single number. It is thirteen numbers arguing.
Our example patient is 54, male, chest pain type 2, resting blood pressure 155, cholesterol 290, fasting blood sugar normal, resting ECG 1, max heart rate 145, exercise-induced angina yes, oldpeak 1.8, slope 1, one major vessel coloured, thal 2. Cholesterol 290 is high, sure. But does it matter more than his heart rate only reaching 145 during exercise, or that he gets chest pain when he exercises? A single number cannot answer that. A model that has seen 500 similar rows can at least rank them.
That ranking is the whole point. Most heart disease prediction machine learning demos stop at a percentage. You cannot do anything with 86.0%. You can do something with “your oldpeak is doing the most damage, then your exercise angina, then your max heart rate”.
What you need
Nothing exotic. Python 3.10 or newer, pandas, scikit-learn, and numpy. That is the entire stack, and it all runs offline. The project ships with its own sample dataset, 500 rows in the UCI column format, so there is no download step and no API key.
The files are small and each one has one job:
heart-risk-calculator/
├── train.py # load data, train the forest, print accuracy
├── predict.py # score one person, top 3 factors, what-if
├── config.py # dataset path, features, example person
├── requirements.txt # pandas, scikit-learn, numpy
├── README.md # setup, demo run, real UCI notes
└── sample_data/
└── heart_sample.csv # 500 rows, 13 features + target
config.py is the control panel: the 13 features, the sample CSV path, the example patient, and the four what-if scenarios. To score a different person, change one dictionary there. train.py answers “how good is this model?” and predict.py answers “what about this person?”
How it works
The model is a Random Forest. Imagine asking 200 doctors the same question, except each doctor only gets a random handful of your test results, and each one answers yes or no: disease or no disease. Then you count the votes. If 172 out of 200 say disease, your risk score is 86.0%. That is literally what happens here: 200 trees, each trained on a slightly different slice of the data, and the risk score is the share voting for disease.

So the score is a proportion, not a prophecy. 86.0% does not mean “you are 86% diseased”. It means 86% of the trees, looking at this sample data, voted disease — a vote count from a demo, not a medical fact.
train.py loads the 500 sample rows — 268 labelled with disease, 232 without — and splits them: 400 to train on, 100 held back for testing. The split is stratified, and the seed is fixed at 42. predict.py trains on all 500 rows, then runs the two tricks that make this project worth building: the top-3 factors and the what-ifs.
The top-3 trick is simple and honest. Take the patient, change one number to the sample median — the middle value, with half the sample above it and half below — and re-score. If the score drops a lot, that number was pushing the risk up. For this sample the medians are age 54, resting blood pressure 131, cholesterol 245, max heart rate 150, and oldpeak 1.0. Do that for all 13 features and sort by the drop. The what-if trick is the same idea with targets you choose: cholesterol 290 down to 200, resting blood pressure 155 down to 120, max heart rate 145 up to 155.
The maths
Each tree is a flowchart of yes-or-no questions: is cholesterol above 240? Is max heart rate below 150? A single tree overfits — it memorises quirks. Two hundred trees, each seeing a random subset of rows and features, average those quirks away. That averaging is the whole trick. There is no equation to memorise, just votes.
Feature importance is the forest telling you which questions it asked most usefully, measured by how much each feature cleaned up the splits across all 200 trees. The importances add up to 1.00. On the sample data the top five are max heart rate at 0.197, oldpeak at 0.170, cholesterol at 0.142, resting blood pressure at 0.119, and age at 0.104 — together 0.732 of the total. At the bottom sit sex at 0.019 and fasting blood sugar at 0.016.
Now the worked example, with the actual numbers from the demo run. The patient scores 86.0%, and the top three factors are:
- Oldpeak, 1.8 → median 1.0: −16.5 points. Oldpeak is how much the ST segment on an ECG dips during exercise; a bigger dip is a worse sign. Setting it to the median drops the score from 86.0% to 69.5% — the single biggest lever for this person.
- Exercise-induced angina, 1 → median 0: −13.0 points. This patient gets chest pain during exercise. Flip that to “no” and the score falls to 73.0%. You cannot flip this number by wishing — it is a symptom, not a setting.
- Max heart rate, 145 → median 150: −9.0 points. Only five beats higher, yet the score drops 9.0 points to 77.0%. Max heart rate is also the most important feature overall at 0.197.
Notice what is not in the top three: cholesterol. It is third overall in global importance at 0.142, but for this specific person it is not one of the three biggest drivers. Global importance and personal importance are different questions, and confusing them is the most common mistake in explainable machine learning.
Then the what-ifs:
- Lower cholesterol, 290 → 200: 75.0%, −11.0 points
- Lower resting blood pressure, 155 → 120: 85.0%, −1.0 point
- More exercise, max heart rate 145 → 155: 73.0%, −13.0 points
- All three together: 56.5%, −29.5 points
Cholesterol helps a lot. Exercise helps more. Blood pressure, on its own, does almost nothing — one single point. And yet all three together drop the score by 29.5 points, more than the individual drops added up: −11.0 plus −1.0 plus −13.0 is −25.0, not −29.5. The extra 4.5 points come from the trees interacting: when several numbers improve at once, the patient lands where far fewer trees vote disease. The model is not adding up independent effects, because the body does not work like that either. Guess which three numbers changed the score, and the answer is “all of them, together”.
Build it
Set up a virtual environment, then install the three dependencies in requirements.txt — pandas, scikit-learn, and numpy. No deep learning framework, no GPU, no cloud account:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtThe training script is train.py. It loads the CSV, splits it, trains the forest, and prints the results:
from sklearn.ensemble import RandomForestClassifier
from config import N_ESTIMATORS, RANDOM_STATE
def train_model(X, y):
"""Fit a Random Forest. 200 trees, fixed seed so results repeat."""
model = RandomForestClassifier(
n_estimators=N_ESTIMATORS, random_state=RANDOM_STATE
)
model.fit(X, y)
return modelThe important line is random_state=RANDOM_STATE, with the seed fixed at 42 in config.py. Without it, every run would shuffle differently and the numbers in this article would not match your numbers. The scoring script is predict.py. Its core is tiny — a function that turns thirteen numbers into a percentage:
def risk_score(model, person):
"""Probability (0-100) the model assigns to class 1 (disease)."""
row = pd.DataFrame([person], columns=FEATURES)
return float(model.predict_proba(row)[0][1]) * 100predict_proba returns the share of trees voting for each class, and [0][1] takes the disease class. The top-3 function in the full code swaps each feature for the sample median and keeps the three biggest drops, and the what-ifs in config.py are the same re-scoring idea with targets you choose: cholesterol 290 → 200, resting blood pressure 155 → 120, max heart rate 145 → 155, and all three together.
Run it with python3 train.py and then python3 predict.py. That is the whole build: two commands, thirteen columns, two hundred trees, and a percentage that finally comes with an explanation attached.
Expected outcome
Here is the exact output you should see. If your numbers differ, check you are running the code from the project folder with the sample CSV in place — and that you did not change the seed. train.py loads 500 rows (268 with disease, 232 without), trains on 400, tests on 100, and prints test accuracy of 69.00% (0.6900).
69.00% means the model got 69 out of the 100 held-out test rows right. The classification report adds detail: for patients without disease, precision 0.683 and recall 0.609; for patients with disease, precision 0.695 and recall 0.759. It spots disease better than it spots its absence.
Then the feature importances, which sum to 1.00, led by max heart rate 0.197, oldpeak 0.170, cholesterol 0.142, resting blood pressure 0.119, and age 0.104.

predict.py prints the score, the top three, and the what-ifs:
Risk score: 86.0%
Top 3 factors pushing this person's score up
(score drop when that one value is set to the sample median):
1. ST depression induced by exercise (oldpeak = 1.8): -16.5 points
2. Exercise-induced angina (0/1) (exang = 1): -13.0 points
3. Max heart rate achieved (thalach = 145): -9.0 points
What-if scenarios:
Lower cholesterol: 290 -> 200 mg/dl: 75.0% (-11.0 points)
Lower resting blood pressure: 155 -> 120 mm Hg: 85.0% (-1.0 points)
More exercise: max heart rate 145 -> 155: 73.0% (-13.0 points)
All three together: 56.5% (-29.5 points)The 69.00% accuracy is not impressive next to a headline-grabbing 95%, and that is fine. A demo that tells the truth about a 500-row sample beats one that overfits its way to a prettier number and explains nothing. All of these metrics are from the built-in sample dataset, not the full UCI dataset.
What broke
Two things broke, and both were my fault for trusting the first version.
The first failure was the sample data itself. My first generator drew every feature from a wide uniform range, which sounded fair and was actually nonsense. The median cholesterol came out at 363.5 — higher than the example patient’s 350 — and the median oldpeak was 3.3. Setting a value “to the median” then meant setting it to something worse than the patient already had, so the top-3 list came out as gibberish and lowering blood pressure somehow raised the risk score by 11.5 points. The fix was realistic centred distributions: cholesterol around 246, blood pressure around 132, max heart rate around 150, oldpeak around 1.0. Medians have to mean “a typical person” or the median-swap trick collapses.
The second failure was saturation. My first example patient was so extreme — cholesterol 350, blood pressure 170, max heart rate 110, oldpeak 3.5 — that the forest voted 97.0% disease and then refused to budge. When 194 out of 200 trees already vote disease, changing one number cannot flip many of them. The fix was a less extreme patient: 54 years old, cholesterol 290, blood pressure 155, max heart rate 145, oldpeak 1.8, scoring 86.0%. At 86.0% there is still room for the what-ifs to move — all the way to 56.5% combined.
Third, the blood pressure what-if still barely moves the score: 155 down to 120 is only −1.0 point on its own. I checked it three ways because I assumed it was a bug. It is not a bug. For this patient, the exercise numbers dominate. It only matters in combination. I kept it in anyway, because a demo that only shows the changes that work is advertising, not engineering.
Download the full project
The full project — train.py, predict.py, config.py, requirements.txt, README.md, and the 500-row sample dataset — is available as a zip:
Premium Download
Get the complete project code
Unzip it, run the two commands, and change the patient in config.py to someone else. Try changing only blood pressure and watch it barely move. Then try all three changes together and watch the forest change its mind. That gap, between what one number does and what three numbers do together, is the entire project. And it is still an educational demo only — not medical advice, not a diagnosis. The model learned from 500 synthetic sample rows. Your heart deserves a doctor, not a Random Forest.
