Heart Disease Prediction (ONNX)
Live demo: https://sayko89.github.io/heart-disease-onnx/ · Format: ONNX + scikit-learn · Task: binary tabular classification
A small, fully reproducible logistic-regression model that estimates the probability of heart disease from 13 clinical attributes in the classic UCI Heart Disease (Cleveland) dataset. The model is exported to ONNX so the very same file can be used in Python, in the browser and on mobile — every runtime returns the same probability for the same input.
The model is intentionally simple: the point of this project is the end-to-end pipeline (train locally → export to ONNX → host for free on the Hugging Face Hub → run client-side).
⚠️ For educational and demonstration purposes only. This model is not a medical device and must not be used to diagnose, treat or make any clinical decision.
Model details
| Architecture | scikit-learn Pipeline(StandardScaler → LogisticRegression) |
| Hyperparameters | L2 regularisation, C=1.0, max_iter=1000, lbfgs solver |
| Decision threshold | 0.5 |
| Random seed | 13 |
| Training environment | Python 3.12.7, scikit-learn 1.5.1 |
| ONNX conversion | skl2onnx, opset 17, zipmap=False |
| ONNX ↔ scikit-learn max. difference | < 1e-6 on the test set (checked automatically at export) |
| Files | model.onnx (portable), model.joblib (scikit-learn pickle), config.json (I/O contract) |
Intended use
- Intended: teaching and demonstrating how to train, export, host and serve a tabular ML model; experimenting with client-side (in-browser) inference.
- Out of scope: any real-world medical screening, diagnosis or triage; use on patients or on populations different from the training data.
Training data
Source: UCI Machine Learning Repository — Heart Disease, Cleveland Clinic Foundation subset (Janosi et al., 1989), in the widely used 303-row CSV form.
Preprocessing. This CSV version has two known issues, both corrected before training:
- Inverted target. In this version
target = 1actually means no disease (patients withtarget = 1have higher maximum heart rate, less exercise angina and fewer blocked vessels). An explicit label is therefore derived:heart_disease = 1 - target(1 = heart disease present, 0 = absent). - Hidden missing values.
ca = 4(5 rows) andthal = 0(2 rows) correspond to missing values in the original data; these 7 rows are removed.
After cleaning: 296 patients, 136 with heart disease (46%) and 160 without. Data were split 70/30 (stratified) into 207 training and 89 test rows.
Input features
The ONNX input is a float32 tensor of shape [n, 13] with columns in this exact order:
| # | Feature | Description | Encoding |
|---|---|---|---|
| 0 | age | Age in years | numeric |
| 1 | sex | Sex | 0 = female, 1 = male |
| 2 | cp | Chest pain type | 0 = asymptomatic, 1 = atypical angina, 2 = non-anginal pain, 3 = typical angina |
| 3 | trestbps | Resting blood pressure on admission (mm Hg) | numeric |
| 4 | chol | Serum cholesterol (mg/dl) | numeric |
| 5 | fbs | Fasting blood sugar > 120 mg/dl | 0 = no, 1 = yes |
| 6 | restecg | Resting electrocardiographic result | 0 = left ventricular hypertrophy, 1 = normal, 2 = ST-T wave abnormality |
| 7 | thalach | Maximum heart rate achieved during exercise test | numeric |
| 8 | exang | Exercise-induced angina | 0 = no, 1 = yes |
| 9 | oldpeak | ST depression induced by exercise relative to rest | numeric |
| 10 | slope | Slope of the peak exercise ST segment | 0 = downsloping, 1 = flat, 2 = upsloping |
| 11 | ca | Number of major vessels (0–3) colored by fluoroscopy | 0–3 |
| 12 | thal | Thallium stress test result | 1 = fixed defect, 2 = normal, 3 = reversible defect |
Evaluation
Hold-out test set (30 %, n = 89)
| Metric | Value |
|---|---|
| Accuracy | 0.8876 |
| ROC AUC | 0.9309 |
| Precision | 0.9697 |
| Recall (sensitivity) | 0.7805 |
| Specificity | 0.9792 |
| F1 score | 0.8649 |
Confusion matrix (rows = actual, columns = predicted):
| Predicted: no disease | Predicted: disease | |
|---|---|---|
| Actual: no disease | 47 | 1 |
| Actual: disease | 9 | 32 |
5-fold stratified cross-validation (all 296 rows)
| Metric | Mean ± std |
|---|---|
| ROC AUC | 0.907 ± 0.0528 |
| Accuracy | 0.8615 ± 0.0508 |
The cross-validated scores are a more reliable estimate than the single hold-out split, given the small dataset.
Feature effects
Coefficients of the logistic regression on standardised features (sorted by magnitude). A positive value means a higher feature value increases the predicted probability of disease.
| Feature | Coefficient | Effect |
|---|---|---|
ca | +0.959 | ↑ higher risk |
sex | +0.907 | ↑ higher risk |
cp | -0.622 | ↓ lower risk |
oldpeak | +0.610 | ↑ higher risk |
thalach | -0.576 | ↓ lower risk |
thal | +0.570 | ↑ higher risk |
trestbps | +0.412 | ↑ higher risk |
exang | +0.394 | ↑ higher risk |
slope | -0.268 | ↓ lower risk |
fbs | -0.194 | ↓ lower risk |
chol | +0.166 | ↑ higher risk |
restecg | -0.164 | ↓ lower risk |
age | -0.144 | ↓ lower risk |
Because several features are categorical codes treated as numbers, these coefficients describe associations in this dataset only and should not be read as causal effects.
How to use
I/O contract
- Input:
input— float32[n, 13], column order =config.json → features - Outputs:
probabilities— float32[n, 2], column order =config.json → classes([0, 1]);label— int64[n](predicted class at threshold 0.5)
config.json also contains human-readable labels, example values, valid ranges and category
options for every feature, so a user interface can be generated from it without hard-coding.
In the browser
Try it at https://sayko89.github.io/heart-disease-onnx/ — the page downloads model.onnx from this repo and runs it locally with onnxruntime-web. No input data leaves the browser.
Python (ONNX Runtime)
import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
sess = ort.InferenceSession(hf_hub_download("saiyko/heart-disease-onnx", "model.onnx"))
x = np.array([[54.0, 1.0, 0.0, 130.0, 246.0, 0.0, 1.0, 150.0, 0.0, 1.0, 1.0, 0.0, 2.0]], dtype=np.float32) # one patient, order = config.json features
proba = sess.run(["probabilities"], {"input": x})[0]
print(f"P(heart disease) = {proba[0, 1]:.4f}")
JavaScript (browser or Node.js)
import * as ort from "onnxruntime-web";
const base = "https://huggingface.co/saiyko/heart-disease-onnx/resolve/main/";
const cfg = await (await fetch(base + "config.json")).json();
const session = await ort.InferenceSession.create(base + "model.onnx");
const values = [54.0, 1.0, 0.0, 130.0, 246.0, 0.0, 1.0, 150.0, 0.0, 1.0, 1.0, 0.0, 2.0]; // order = cfg.features
const input = new ort.Tensor("float32", Float32Array.from(values), [1, values.length]);
const out = await session.run({ input });
console.log("P(heart disease) =", out.probabilities.data[1]);
scikit-learn
import joblib
from huggingface_hub import hf_hub_download
model = joblib.load(hf_hub_download("saiyko/heart-disease-onnx", "model.joblib"))
print(model.predict_proba([[54.0, 1.0, 0.0, 130.0, 246.0, 0.0, 1.0, 150.0, 0.0, 1.0, 1.0, 0.0, 2.0]]))
⚠️
model.joblibis a pickle file: only load it from sources you trust, and use the same scikit-learn version (1.5.1). Prefermodel.onnx, which is version-independent and safe to load.
Limitations and biases
- Missed cases. At the default 0.5 threshold the model misses 9 of 41 test patients who actually have heart disease (recall 0.7805), while raising only 1 false alarm(s). In a screening setting false negatives are the costlier error, so a lower threshold would be needed — which in turn produces more false alarms.
- Small, old dataset. 296 patients from a single US clinic, collected in the 1980s. Performance on other hospitals, countries or time periods is unknown and likely lower.
- Imbalanced demographics. About two thirds of the patients are male and most are middle-aged, so the model is less reliable for women and for younger or older patients.
- Selected population. All patients were referred for coronary angiography, i.e. they were already suspected of heart disease; the base rate is far higher than in the general population, so probabilities are not calibrated for screening.
- Simple model. Categorical codes are used as ordinal numbers and no interactions are modelled.
- Uncertain dataset version. The category encodings of this CSV variant were reconstructed by matching counts against the original UCI files; see Preprocessing above.
Ethical considerations
Health predictions can cause harm if trusted blindly. Do not present this model's output to patients as a diagnosis. Because the model file is public and inference runs on the client, it must never be retrained on private patient data and published this way.
Citation
Dataset:
@misc{janosi1989heart,
author = {Janosi, Andras and Steinbrunn, William and Pfisterer, Matthias and Detrano, Robert},
title = {Heart Disease},
year = {1989},
howpublished = {UCI Machine Learning Repository},
doi = {10.24432/C52P4X}
}
License
Model and code: CC BY 4.0, matching the license of the UCI Heart Disease dataset.