/ Модель

Характеристики

Лицензия
CC BY 4.0
Библиотека
sklearn
Опубликована
30 окт 2026

heart-disease-onnx

Классификация таблицTable → label3 профессии

Компактный классификатор ONNX оценивает вероятность заболевания сердца по 13 клиническим признакам для образовательных демонстраций.

0скачиваний за 30 дней1лайквеса обновлены30 окт 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Модель sai yko/heart-disease-onnx — компактный классификатор на основе scikit-learn Pipeline со стандартизацией признаков и логистической регрессией, экспортированный в формат ONNX. Она оценивает вероятность наличия заболевания сердца по 13 клиническим признакам из набора UCI Heart Disease (Cleveland) и выдаёт вероятности двух классов и метку класса при пороге 0,5. Проект предназначен для демонстрации воспроизводимого цикла обучения, экспорта и локального запуска в Python, браузере или на мобильном устройстве; модель разработана автором репозитория Saiyko.

Карточка приводит результаты на небольшой выборке: ROC AUC 0,907 ± 0,0528 при пятифолдовой кросс-валидации. Это модель для образовательных и демонстрационных сценариев, а не медицинское устройство. Данные включают 296 пациентов одной клиники в США, собранные в 1980-х годах; в тестовой выборке при пороге 0,5 пропущено 9 из 41 случаев заболевания. Категориальные коды обрабатываются как числа, а коэффициенты отражают ассоциации, а не причинные эффекты. Лицензия — CC BY 4.0.

Сценарии применения

  • демонстрация бинарной классификации клинических табличных данных
  • локальная оценка вероятности заболевания сердца по 13 признакам
  • встраивание учебной модели в браузерное приложение
  • проверка запуска классификатора ONNX в Python или Node.js

Ограничения

Модель не предназначена для диагностики или клинических решений. Она обучена на небольшой старой выборке пациентов одной клиники, может пропускать случаи заболевания, а её вероятности и качество на других популяциях не установлены.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

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

Architecturescikit-learn Pipeline(StandardScaler → LogisticRegression)
HyperparametersL2 regularisation, C=1.0, max_iter=1000, lbfgs solver
Decision threshold0.5
Random seed13
Training environmentPython 3.12.7, scikit-learn 1.5.1
ONNX conversionskl2onnx, opset 17, zipmap=False
ONNX ↔ scikit-learn max. difference< 1e-6 on the test set (checked automatically at export)
Filesmodel.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:

  1. Inverted target. In this version target = 1 actually means no disease (patients with target = 1 have 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).
  2. Hidden missing values. ca = 4 (5 rows) and thal = 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:

#FeatureDescriptionEncoding
0ageAge in yearsnumeric
1sexSex0 = female, 1 = male
2cpChest pain type0 = asymptomatic, 1 = atypical angina, 2 = non-anginal pain, 3 = typical angina
3trestbpsResting blood pressure on admission (mm Hg)numeric
4cholSerum cholesterol (mg/dl)numeric
5fbsFasting blood sugar > 120 mg/dl0 = no, 1 = yes
6restecgResting electrocardiographic result0 = left ventricular hypertrophy, 1 = normal, 2 = ST-T wave abnormality
7thalachMaximum heart rate achieved during exercise testnumeric
8exangExercise-induced angina0 = no, 1 = yes
9oldpeakST depression induced by exercise relative to restnumeric
10slopeSlope of the peak exercise ST segment0 = downsloping, 1 = flat, 2 = upsloping
11caNumber of major vessels (0–3) colored by fluoroscopy0–3
12thalThallium stress test result1 = fixed defect, 2 = normal, 3 = reversible defect

Evaluation

Hold-out test set (30 %, n = 89)

MetricValue
Accuracy0.8876
ROC AUC0.9309
Precision0.9697
Recall (sensitivity)0.7805
Specificity0.9792
F1 score0.8649

Confusion matrix (rows = actual, columns = predicted):

Predicted: no diseasePredicted: disease
Actual: no disease471
Actual: disease932

5-fold stratified cross-validation (all 296 rows)

MetricMean ± std
ROC AUC0.907 ± 0.0528
Accuracy0.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.

FeatureCoefficientEffect
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.joblib is a pickle file: only load it from sources you trust, and use the same scikit-learn version (1.5.1). Prefer model.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.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · sklearn

Нельзя запустить

Табличные модели пока не поддерживаются.

Ревизия весов
f5ef526

0 моделей