Skip to main content

Train, save, and run fraud detection on transaction data. Random Forest classifier with clean API.

Project description

fraud-shield

PyPI MIT License GitHub Python scikit-learn

Train, save, and run fraud detection on transaction data. 94% balanced accuracy on the Kaggle dataset. One class. Clean API.

Built from a production Random Forest classifier for credit card fraud detection on imbalanced datasets. Handles the hard parts — class imbalance, balanced accuracy, probability calibration — so you don't have to.

fraud-shield demo

When to use this

Use fraud-shield when:

  • You need a fraud detection classifier you can train and deploy in under 10 lines of Python
  • Your dataset is heavily imbalanced (fraud cases are < 1% of transactions — raw accuracy is meaningless here)
  • You want probability scores and confidence levels per transaction, not just binary labels
  • You need save/load support so you train once and deploy the pickled model

Not the right fit if you need real-time streaming fraud detection, rule-based engines, or graph-based fraud networks. fraud-shield is a supervised batch classifier built on Random Forest — best suited for tabular transaction data.


Why not sklearn directly?

You can absolutely use sklearn.ensemble.RandomForestClassifier directly. fraud-shield wraps it with the patterns that fraud data specifically requires:

  • Balanced accuracy by default — raw accuracy on fraud data is meaningless (a model that predicts every transaction as legitimate gets ~99.8% accuracy while catching zero fraud)
  • SMOTE-style class weighting — handles the imbalance automatically
  • Confidence tiershigh / medium / low based on probability thresholds, not just a 0/1 label
  • One-liner train/save/load — no boilerplate

Install

pip install fraud-shield

Or from source:

git clone https://github.com/iamadhitya1/fraud-shield
pip install -e fraud-shield/

Quick Start

from fraudshield import FraudDetector

# Train
detector = FraudDetector()
detector.train("transactions.csv", target_col="Class")
detector.save("fraud_model.pkl")

# Predict single transaction
result = detector.predict({
    "V1": -1.36, "V2": -0.07, "V3": 2.54, "Amount": 149.62
    # ... all feature columns
})

print(result.label)             # "FRAUD" or "LEGITIMATE"
print(result.fraud_probability) # 0.9423
print(result.confidence)        # "high"

Train

detector = FraudDetector(
    n_estimators=100,              # number of trees
    random_state=42,               # reproducibility
    high_confidence_threshold=0.80,
    low_confidence_threshold=0.40,
)

metrics = detector.train("creditcard.csv", target_col="Class", verbose=True)
# [fraud-shield] Training on 199364 samples...
# [fraud-shield] Training complete.
#   Balanced Accuracy : 0.9412
#   F1 Score (macro)  : 0.9318
#   ROC-AUC           : 0.9876

Compatible with: Kaggle Credit Card Fraud Detection dataset and any binary classification dataset with 0/1 labels.


Predict

Single transaction

result = detector.predict(transaction_dict)

result.is_fraud           # True / False
result.fraud_probability  # 0.0 – 1.0
result.confidence         # "high" / "medium" / "low"
result.label              # "FRAUD" / "LEGITIMATE"
result.to_dict()          # { is_fraud, fraud_probability, confidence, label }

Batch prediction

import pandas as pd

df = pd.read_csv("new_transactions.csv")
results_df = detector.predict_batch(df)

# Adds columns: fraud_probability, is_fraud, confidence, label
print(results_df[["Amount", "fraud_probability", "label"]].head())

Evaluate

metrics = detector.evaluate("test_data.csv", target_col="Class")

# Returns dict with:
# balanced_accuracy, precision_macro, recall_macro,
# f1_macro, roc_auc, confusion_matrix, classification_report

Feature Importances

top = detector.feature_importances(top_n=10)
print(top)
# V14    0.1821
# V17    0.1342
# V12    0.1089
# ...

Save & Load

# Save
detector.save("fraud_model.pkl")

# Load in another script
detector = FraudDetector.load("fraud_model.pkl")
result = detector.predict(transaction)

Why balanced accuracy?

Raw accuracy is misleading on fraud data — a model that predicts every transaction as legitimate achieves ~99.8% accuracy while catching zero fraud. fraud-shield uses balanced accuracy by default, which averages recall across both classes and penalizes models that ignore the minority class.


Dataset

The included example targets the Kaggle Credit Card Fraud Detection dataset:

  • 284,807 transactions
  • 492 fraud cases (0.17%)
  • Features: V1–V28 (PCA-anonymized), Amount, Time

Author

M. Adhitya — Founder, Rewrite Labs

License

MIT © 2025 M. Adhitya

Built at Rewrite Labs

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fraud_shield-1.0.2.tar.gz (8.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fraud_shield-1.0.2-py3-none-any.whl (8.2 kB view details)

Uploaded Python 3

File details

Details for the file fraud_shield-1.0.2.tar.gz.

File metadata

  • Download URL: fraud_shield-1.0.2.tar.gz
  • Upload date:
  • Size: 8.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for fraud_shield-1.0.2.tar.gz
Algorithm Hash digest
SHA256 e61a8ebe9fa040308b5f12e05dc176fe854c49ea1e8092a6a82b5ebb64210649
MD5 c88611777f2478e5cfe3055d2aafed3e
BLAKE2b-256 84050b25932d22c5fc474757f49703558f4d3b51ffbd815014d2d570f62db640

See more details on using hashes here.

File details

Details for the file fraud_shield-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: fraud_shield-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 8.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for fraud_shield-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9cc46eec1bcf9b7367669c9422ecbc2ea12b9dc62e43df3660117728002d3d73
MD5 1b5286a26c52d07569ab8d278d330555
BLAKE2b-256 cb96003522ac73e78903eafc2f49c193fdd59664b1ae110c9f95a98d3a9c7e0d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page