Creating a Python script for fraud detection
The user seems to want a ready-to-run Python script for detecting fraudulent transactions using machine learning. I should keep it concise while being informative. A classic dataset to use could be Kaggle's creditcard.csv, but they haven't specified one. I’ll plan to write a script that reads a CSV, preprocesses the data, trains a model like RandomForest or XGBoost, and evaluates it with metrics such as ROC-AUC and precision-recall. I should include usage instructions and requirements for adaptability.Building the Python script structure
I’ll focus on using stable libraries like pandas, scikit-learn, and numpy for the script. Handling imbalanced data is crucial, so I’ll set the class_weight to "balanced" in the model, while keeping things simple with that approach.
The pipeline will include loading the CSV, separating features and the 'is_fraud' column, and using stratified train-test splits. I’ll preprocess the data, apply a tree-based model like RandomForestClassifier, and evaluate with metrics such as ROC-AUC and classification reports. Finally, I’ll ensure to wrap the script for easy adaptation and include comments for clarity.Creating the fraud detection script
I’m thinking about creating a script named fraud_detection.py, where I’ll parse arguments like --data_path and --model_output. Though hardcoding data.csv simplifies things, professionals usually prefer using arguments for flexibility. Since the user didn't specify, I'll lean towards customization while keeping the code self-contained and readable.
At the top, I’ll include an explanation stating this is a complete standalone script for training a fraud detection model. I’ll ensure to import necessary libraries like argparse, pandas, numpy, and sklearn components while addressing the import adjustments needed for joblib.Defining the script functions
I’m considering whether the user has the imbalanced-learn library installed, but I think it’s safer to skip that for now. I’ll start by creating a data loading function that reads a CSV and separates features from the target column.
Then, I’ll define a preprocessor function to handle numeric and categorical features, using pipelines with scaling and one-hot encoding. In the main training function, I’ll load the data, split it into training and test sets, and fit a RandomForest model. Finally, I’ll include a function for predicting a single instance, although it might not be needed right away. I want to ensure clarity in the usage instructions.Finalizing the Python script with CLI
Here is a complete Python script that trains a fraud detection model using arguments for data_path, target, and model_out. I'll add an optional prediction subcommand, but it might be simpler to maintain the script focused on training and evaluation.
I’ll show how to load the model for making predictions on new transactions afterward. I'll include installation instructions and note handling imbalanced data with class_weight. I’ll also mention typical features like transaction amount and time, while keeping everything general. The script needs to ensure compatibility and memory efficiency with OneHotEncoder and StandardScaler. I'll keep the output straightforward, without unnecessary complexity. Here is a complete, self-contained Python script that trains a fraud-detection model using machine learning (scikit-learn) and evaluates it.
It assumes:
- Your data is in a CSV file.
- The target column is named
is_fraud (0 = legitimate, 1 = fraudulent).
You can change that via a command-line argument.
fraud_detection.py
#!/usr/bin/env python3
"""
Train a machine learning model to detect fraudulent transactions.
Usage:
python fraud_detection.py --data_path transactions.csv \
--target is_fraud \
--model_out fraud_model.joblib
"""
import argparse
import joblib
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import (
classification_report,
confusion_matrix,
roc_auc_score,
average_precision_score,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def load_data(data_path: str, target_col: str):
"""Load data from CSV and split into features X and target y."""
df = pd.read_csv(data_path)
if target_col not in df.columns:
raise ValueError(f"Target column '{target_col}' not found in CSV.")
y = df[target_col]
X = df.drop(columns=[target_col])
return X, y
def build_preprocessor(X: pd.DataFrame) -> ColumnTransformer:
"""Create preprocessing pipeline for numeric and categorical columns."""
numeric_features = X.select_dtypes(include=["int64", "float64"]).columns.tolist()
categorical_features = X.select_dtypes(
include=["object", "category", "bool"]
).columns.tolist()
numeric_transformer = Pipeline(
steps=[
("scaler", StandardScaler()),
]
)
categorical_transformer = Pipeline(
steps=[
("onehot", OneHotEncoder(handle_unknown="ignore")),
]
)
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
remainder="drop", # drop any columns not listed above
)
return preprocessor
def train_model(
data_path: str,
target_col: str = "is_fraud",
model_out: str = "fraud_model.joblib",
test_size: float = 0.2,
random_state: int = 42,
):
# Load data
X, y = load_data(data_path, target_col)
# Train/validation split (stratified to preserve fraud ratio)
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=test_size,
random_state=random_state,
stratify=y,
)
print(f"Loaded {len(X)} rows.")
print(f"Train size: {len(X_train)}, Test size: {len(X_test)}")
print(f"Fraud rate in full data: {y.mean():.4f}")
# Preprocessing
preprocessor = build_preprocessor(X_train)
# Model: Random Forest with class_weight='balanced' for imbalanced data
clf = RandomForestClassifier(
n_estimators=300,
max_depth=None,
n_jobs=-1,
random_state=random_state,
class_weight="balanced", # important for fraud detection
)
# Full pipeline: preprocessing + model
model = Pipeline(
steps=[
("preprocessor", preprocessor),
("clf", clf),
]
)
# Train
print("\nTraining model...")
model.fit(X_train, y_train)
# Evaluate
print("\nEvaluating on test set...")
y_pred = model.predict(X_test)
if hasattr(model, "predict_proba"):
y_proba = model.predict_proba(X_test)[:, 1]
else:
# Fallback for models without predict_proba
y_proba = model.decision_function(X_test)
print("\nClassification report:")
print(classification_report(y_test, y_pred, digits=4))
cm = confusion_matrix(y_test, y_pred)
tn, fp, fn, tp = cm.ravel()
print("Confusion matrix (TN, FP, FN, TP):")
print(cm)
roc_auc = roc_auc_score(y_test, y_proba)
pr_auc = average_precision_score(y_test, y_proba)
print(f"\nROC-AUC: {roc_auc:.4f}")
print(f"PR-AUC (Average Precision): {pr_auc:.4f}")
print(f"Precision on predicted frauds: {tp / (tp + fp + 1e-9):.4f}")
print(f"Recall on frauds (TPR): {tp / (tp + fn + 1e-9):.4f}")
# Save model
joblib.dump(model, model_out)
print(f"\nModel saved to: {model_out}")
def parse_args():
parser = argparse.ArgumentParser(
description="Train a fraud detection model using machine learning."
)
parser.add_argument(
"--data_path",
type=str,
required=True,
help="Path to CSV file containing transactions.",
)
parser.add_argument(
"--target",
type=str,
default="is_fraud",
help="Name of the target column (default: is_fraud).",
)
parser.add_argument(
"--model_out",
type=str,
default="fraud_model.joblib",
help="Filename to save the trained model (default: fraud_model.joblib).",
)
parser.add_argument(
"--test_size",
type=float,
default=0.2,
help="Fraction of data used for test set (default: 0.2).",
)
parser.add_argument(
"--random_state",
type=int,
default=42,
help="Random seed (default: 42).",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
train_model(
data_path=args.data_path,
target_col=args.target,
model_out=args.model_out,
test_size=args.test_size,
random_state=args.random_state,
)
Installation
pip install pandas scikit-learn joblib
Example usage
python fraud_detection.py --data_path transactions.csv --target is_fraud
This will:
- Train a fraud-detection model.
- Print metrics (confusion matrix, ROC-AUC, PR-AUC, etc.).
- Save the trained pipeline (preprocessing + model) to
fraud_model.joblib.
Using the trained model to score new transactions
import joblib
import pandas as pd
# Load saved model
model = joblib.load("fraud_model.joblib")
# Example: new transactions as a DataFrame
new_tx = pd.DataFrame([
{
"amount": 123.45,
"merchant_category": "electronics",
"country": "US",
"card_present": 0,
"hour_of_day": 23,
# ... other feature columns, same names as training data ...
}
])
fraud_proba = model.predict_proba(new_tx)[:, 1]
fraud_label = model.predict(new_tx)
print("Fraud probability:", fraud_proba[0])
print("Predicted label (0=legit, 1=fraud):", fraud_label[0])
If you share your column names or a sample of your data, I can tailor the script more precisely to your dataset (including better feature engineering or model choices).