Tabular Classification
Scikit-learn
Joblib
fraud-detection
logistic-regression
baseline
Eval Results (legacy)
Instructions to use Marvinds/fraud-baseline-logreg with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Scikit-learn
How to use Marvinds/fraud-baseline-logreg with Scikit-learn:
from huggingface_hub import hf_hub_download import joblib model = joblib.load( hf_hub_download("Marvinds/fraud-baseline-logreg", "sklearn_model.joblib") ) # only load pickle files from sources you trust # read more about it here https://skops.readthedocs.io/en/stable/persistence.html - Notebooks
- Google Colab
- Kaggle
Download train.py from Marvinds/fraud-baseline-logreg: direct link, hf CLI and curl.
- Browser
- Download file 3.46 kB
-
https://huggingface.co/Marvinds/fraud-baseline-logreg/resolve/main/train.py
- Command line
-
hf download hf://Marvinds/fraud-baseline-logreg/train.py
-
curl -L -o train.py https://huggingface.co/Marvinds/fraud-baseline-logreg/resolve/main/train.py
3.46 kB
| # /// script | |
| # requires-python = ">=3.9" | |
| # dependencies = ["numpy>=1.26", "pandas>=2.1", "scikit-learn>=1.4", "joblib>=1.3"] | |
| # /// | |
| """Train a logistic-regression fraud baseline on synthetic-bank-transactions. | |
| Usage: uv run train.py --data ../01-synthetic-bank-transactions/data/transactions.csv | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| import joblib | |
| import numpy as np | |
| import pandas as pd | |
| import sklearn | |
| from sklearn.compose import ColumnTransformer | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.metrics import average_precision_score, precision_recall_curve, roc_auc_score | |
| from sklearn.pipeline import Pipeline | |
| from sklearn.preprocessing import OneHotEncoder, StandardScaler | |
| NUMERIC = ["log_amount", "amount_vs_avg", "txn_count_24h", "is_foreign", "is_new_device", "is_night"] | |
| CATEGORICAL = ["merchant_category", "channel"] | |
| def features(df: pd.DataFrame) -> pd.DataFrame: | |
| out = df.copy() | |
| out["log_amount"] = np.log1p(out["amount_idr"]) | |
| out["is_night"] = out["hour"].between(0, 4).astype(int) | |
| return out[NUMERIC + CATEGORICAL] | |
| def recall_at_precision(y, p, target): | |
| precision, recall, _ = precision_recall_curve(y, p) | |
| ok = recall[precision >= target] | |
| return float(ok.max()) if len(ok) else 0.0 | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--data", type=Path, default=Path("../01-synthetic-bank-transactions/data/transactions.csv")) | |
| parser.add_argument("--out", type=Path, default=Path("model")) | |
| args = parser.parse_args() | |
| df = pd.read_csv(args.data, parse_dates=["timestamp"]).sort_values("timestamp") | |
| cut = int(len(df) * 0.8) | |
| train, test = df.iloc[:cut], df.iloc[cut:] | |
| pipe = Pipeline( | |
| [ | |
| ("prep", ColumnTransformer([ | |
| ("num", StandardScaler(), NUMERIC), | |
| ("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL), | |
| ])), | |
| ("clf", LogisticRegression(max_iter=1000, class_weight="balanced")), | |
| ] | |
| ) | |
| pipe.fit(features(train), train["is_fraud"]) | |
| p = pipe.predict_proba(features(test))[:, 1] | |
| y = test["is_fraud"].to_numpy() | |
| metrics = { | |
| "split": "time-based 80/20", | |
| "test_rows": int(len(test)), | |
| "test_fraud_rate": round(float(y.mean()), 4), | |
| "roc_auc": round(roc_auc_score(y, p), 4), | |
| "pr_auc": round(average_precision_score(y, p), 4), | |
| "recall_at_precision_0.5": round(recall_at_precision(y, p, 0.5), 4), | |
| "recall_at_precision_0.8": round(recall_at_precision(y, p, 0.8), 4), | |
| } | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| model_path = args.out / "model.joblib" | |
| joblib.dump(pipe, model_path) | |
| (args.out / "model.joblib.sha256").write_text(hashlib.sha256(model_path.read_bytes()).hexdigest() + "\n") | |
| names = pipe.named_steps["prep"].get_feature_names_out() | |
| coefs = pipe.named_steps["clf"].coef_[0] | |
| meta = { | |
| "trained_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), | |
| "sklearn_version": sklearn.__version__, | |
| "features": NUMERIC + CATEGORICAL, | |
| "metrics": metrics, | |
| "coefficients": {n: round(float(c), 4) for n, c in sorted(zip(names, coefs), key=lambda x: -abs(x[1]))}, | |
| } | |
| (args.out / "metrics.json").write_text(json.dumps(meta, indent=2) + "\n") | |
| print(json.dumps(metrics, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |