/ Модель

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

Лицензия
MIT
Библиотека
sklearn

credit-card-fraud

Классификация таблицTable → label3 профессии
0скачиваний за 30 дней1лайквеса обновлены25 сен 2026

Описание модели

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

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

shalev396/credit-card-fraud — модель классификации табличных данных для выявления потенциально мошеннических операций по кредитным картам. Разработчик обучил два варианта на наборе ULB: случайный лес smote_rf, выбранный вариантом по умолчанию, и альтернативную нейросеть Keras MLP. Лес содержит 100 деревьев; MLP имеет архитектуру 30–64–32–16–1 и 4 609 параметров. Для признаков V1–V28 используются уже PCA-преобразованные значения, а Time и Amount масштабируются. Модель принимает строки операций в схеме Kaggle Credit Card Fraud и возвращает оценку мошенничества и метку по порогу; для smote_rf порог по умолчанию равен 0,57.

Модель предназначена для экспериментов и оценки операций в том же пространстве признаков, что и исходный набор. На тестовой выборке для smote_rf указаны PR-AUC 0,802, полнота 69 из 95 мошеннических операций и 6 ложных срабатываний при описанном пороге. Эти результаты относятся к данным 2013 года и не подтверждают пригодность для современных платежей. Признаки V1–V28 получены PCA из нераскрытых банковских данных, поэтому модель нельзя напрямую применять к сырым транзакциям других источников; оценки вероятности не калиброваны. README обозначает проект как учебный и не предназначенный для принятия реальных платёжных решений. Лицензия репозитория — MIT.

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

  • поиск подозрительных операций в данных формата Kaggle Credit Card Fraud
  • ранжирование транзакций по оценке риска мошенничества
  • эксперименты с порогом между полнотой выявления и ложными тревогами

Ограничения

Модель работает только с признаками V1–V28, Time и Amount в формате исходного набора; PCA-признаки нельзя получить из произвольных сырых транзакций. Данные охватывают два дня 2013 года, вероятности не калиброваны, а README прямо предостерегает от использования для реальных платёжных решений.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

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

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

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

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

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

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

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

Открыть на Hugging Face

Credit Card Fraud Detector

Scores credit-card transactions for fraud. The default model, smote_rf, is a random forest trained on SMOTE-oversampled data; a Keras MLP (keras_mlp) is included as an alternative. Both were trained on the ULB credit-card fraud dataset. On the held-out test split (56,746 transactions, 95 frauds), the default model catches 69 of 95 frauds and raises 6 false alarms, for a PR-AUC of 0.802 at its tuned threshold of 0.57 (run of 2026-09-25, metrics.json).

Model

  • Input: transactions with the Kaggle columns Time, V1..V28, Amount, as a pandas DataFrame, a CSV path, CSV text, a list of row dicts or {"rows": [...]}. Other columns, such as the label Class, are ignored.
  • Preprocessing (model.to_features): V1..V28 are used as-is (the bank released them already PCA-transformed). Amount and Time are scaled with a RobustScaler (median/IQR fit on the training split, scaler.joblib). This gives 30 float32 features.
  • smote_rf (default, model.joblib): RandomForestClassifier with 100 trees and scikit-learn defaults. It was fit on training rows that SMOTE balanced to 50/50. SMOTE only runs at training time, so the file holds just the fitted forest. P(fraud) is the forest's vote share. A row is flagged when P(fraud) >= 0.57, the threshold that maximised F1 on the validation split.
  • keras_mlp (alternative, model.keras): Dense 30-64-32-16-1 with ReLU, dropout 0.3 and a sigmoid head (4,609 parameters, float32). It was trained with balanced class weights and early stopping. The class weights push its probabilities up, so its tuned threshold is higher (0.937).
  • config.json holds the input schema, each model's tuned threshold and validation PR-AUC, the default model and the library versions. model.py loads it all (model.load(path).predict(...)).

Output of predict(data, model="best", threshold=None):

{"model": "smote_rf", "threshold": 0.57, "n_rows": 10, "n_flagged": 3,
 "rows": [{"row": 0, "fraud_probability": 0.98, "is_fraud": true}, ...]}

threshold=None uses the model's tuned threshold. Pass your own threshold to trade recall against false alarms.

Usage

Python

from huggingface_hub import hf_hub_download, snapshot_download
import sys
path = snapshot_download("shalev396/credit-card-fraud")
sys.path.insert(0, path)
import model
predictor = model.load(path, device="cpu")   # CPU only (scikit-learn + TensorFlow)
csv = hf_hub_download("shalev396/credit-card-fraud", "examples/mixed_transactions.csv", repo_type="space")
print(predictor.predict(csv))                  # or a DataFrame / CSV text / list of row dicts
print(predictor.predict(csv, model="keras_mlp", threshold=0.5))

Space API (free, public): the Space exposes /predict with inputs (csv_file, model, threshold) and outputs [result, seconds, device]; see its README for curl, @gradio/client and gradio_client examples.

Inference Endpoint: this repo has a handler.py, so it can be deployed as a dedicated API from the model page (Deploy → Inference Endpoints, CPU hardware is enough; dependencies in requirements.txt). Request body:

{"inputs": "Time,V1,V2,...,V28,Amount\n<one line of 30 numbers per transaction>\n",
 "parameters": {"model": "best", "threshold": 0.57}}

inputs can also be a list of row dicts or {"rows": [...]}. Both parameters are optional. The response is the predict dict above.

Training

  • Data: 284,807 transactions made by European cardholders over two days in September 2013, collected by Worldline and the ULB Machine Learning Group. Of these, 492 are frauds (0.17 %). The data is downloaded from Kaggle mlg-ulb/creditcardfraud, with OpenML data_id=1597 as a fallback. Exact duplicate rows are dropped so that a transaction cannot appear in two splits, which leaves 283,726 rows and 473 frauds.
  • Split: stratified 60/20/20 into train / validation / test: 170,235 / 56,745 / 56,746 rows with 284 / 94 / 95 frauds.
  • Selection (the test split never influences a choice): for each model, the decision threshold is set to maximise F1 on validation. The default model is the one with the highest validation PR-AUC (average precision). The best scikit-learn variant and the MLP are exported. Test metrics are then computed once for every variant.
  • Hardware / time: CPU only. Fitting all 12 candidates took 383 s in this run (6 threads on a desktop CPU shared with other jobs; 15.6 min wall time for the whole notebook); an earlier 20-thread run of the old train.py pipeline took about 3 minutes end to end.
  • Full code: training/ (the notebook drives every step) · Colab

Experiments

Twelve candidates, all fit on the same train split and scored on the same features:

GroupVariantsIdea
Baselinesbaseline_logreg, baseline_rfimbalanced data as-is
NearMiss-1 undersamplingnearmiss_{logreg,knn,dtree,rf,svc}keep only the legit rows closest to frauds (the RBF SVM is Platt-calibrated)
SMOTE oversamplingsmote_{logreg,knn,dtree,rf}synthesise frauds up to a 50/50 balance
Neural netkeras_mlpDense 30-64-32-16-1, balanced class weights, early stopping on a slice of the train split

Resampling runs inside an imblearn Pipeline, so it only touches the rows a model is fit on. All variants, ranked by validation PR-AUC (the selection metric). Each variant's test metrics are at its own tuned threshold; the deployed model is in bold:

variantval PR-AUCthresholdtest PR-AUCtest ROC-AUCtest F1test precisiontest recall
smote_rf (deployed)0.88390.5700.80160.95980.81180.92000.7263
baseline_rf0.87690.3300.79830.91890.81610.89870.7474
baseline_logreg0.80240.1420.69390.95580.77270.83950.7158
smote_logreg0.76581.0000.71790.95820.79770.88460.7263
keras_mlp (exported alternative)0.73330.9370.68380.93650.79120.82760.7579
smote_knn0.68191.0000.54490.91000.70710.67960.7368
nearmiss_rf0.59521.0000.57710.88550.72620.83560.6421
nearmiss_svc0.41631.0000.35540.92330.43970.67390.3263
smote_dtree0.36491.0000.26830.83600.50000.39750.6737
nearmiss_logreg0.05851.0000.04740.89660.13480.09060.2632
nearmiss_knn0.00551.0000.00470.78110.01040.00520.8211
nearmiss_dtree0.00231.0000.00220.61680.00440.00220.9368

Model comparison Keras MLP training curves Precision-recall curves

  • Why PR-AUC: frauds are 0.17 % of rows, so ROC-AUC barely separates the models. smote_logreg scores a test ROC-AUC of 0.958, close to smote_rf at 0.960, but its PR-AUC is 0.718 against 0.802. nearmiss_logreg scores a ROC-AUC of 0.897 with a PR-AUC of 0.047. NearMiss discards all but a few hundred legit rows, and its precision collapses.
  • The selection margin is small: smote_rf beats baseline_rf on validation PR-AUC by 0.884 to 0.877, which is within noise for 94 validation frauds. On test the two models are equivalent: PR-AUC 0.802 vs 0.798 and F1 0.812 vs 0.816.
  • The MLP stops early after 7 epochs (best early-stopping PR-AUC at epoch 2) and ends below both random forests and plain logistic regression on validation PR-AUC (0.733).
  • What changed from the earlier version of this project: the original pipeline ranked models by test ROC-AUC at a fixed 0.5 threshold. It picked smote_logreg, which had precision 0.059 and F1 0.111 on its test split, while its plain random forest had F1 0.874 and PR-AUC 0.861. Those numbers come from a documented earlier run of the old pipeline, which used an 80/20 split with duplicates kept and no validation split. They are not directly comparable with the table above, which trains on 60 % of the rows and has no duplicate leakage.

Evaluation

Default model (smote_rf) on the test split, at its tuned threshold of 0.57:

metric (test)value
pr_auc0.8016
roc_auc0.9598
f10.8118
precision0.9200
recall0.7263

Confusion matrix on the test split: 69 of 95 frauds caught (recall 0.726), 6 false alarms among 56,651 legit transactions (precision 0.920).

Threshold tuning Confusion matrix

Limitations

  • Only works on this dataset's feature space. V1..V28 come from an unpublished PCA of undisclosed bank features, so the model cannot score raw transactions from any other source.
  • Old, narrow data. Two days of European card traffic from 2013. Fraud patterns drift, and nothing here was validated on later data.
  • Few positives. There are 95 test frauds, so each missed fraud moves recall by about 1 percentage point. Treat the metrics as estimates with wide error bars.
  • Scores are not calibrated probabilities. Forest votes come from SMOTE-balanced data, and the MLP was trained with class weights. Use fraud_probability for ranking and thresholding only.
  • Max-F1 is one operating point. When a missed fraud and a false alarm have different costs, choose your own threshold (the threshold argument).
  • Time counts seconds since the first transaction in the two-day window, so it means nothing for new data.
  • Educational portfolio project. Not for real payment decisions.

Dataset credit: Dal Pozzolo, Caelen, Johnson and Bontempi, Calibrating Probability with Undersampling for Unbalanced Classification, IEEE CIDM 2015 (Worldline and ULB Machine Learning Group).

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

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

GPU в ailist

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

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

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

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

0 моделей