Deploy fraud detection app v1.0
Browse files- README.md +29 -6
- app.py +222 -0
- requirements.txt +6 -0
README.md
CHANGED
|
@@ -1,13 +1,36 @@
|
|
| 1 |
---
|
| 2 |
title: Credit Card Fraud Detector
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.14.0
|
| 8 |
-
python_version: '3.13'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Credit Card Fraud Detector
|
| 3 |
+
emoji: 🔍
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: "6.14.0"
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
tags:
|
| 12 |
+
- fraud-detection
|
| 13 |
+
- xgboost
|
| 14 |
+
- classification
|
| 15 |
---
|
| 16 |
|
| 17 |
+
# 🔍 Credit Card Fraud Detector
|
| 18 |
+
|
| 19 |
+
Modelo XGBoost entrenado con SMOTE para detectar transacciones fraudulentas en tarjetas de crédito.
|
| 20 |
+
|
| 21 |
+
## Características
|
| 22 |
+
|
| 23 |
+
- **Modelo**: XGBoost con SMOTE para manejo de desbalance extremo (0.58% fraude)
|
| 24 |
+
- **ROC-AUC**: 0.994
|
| 25 |
+
- **F1 (calibrado)**: 0.74
|
| 26 |
+
- **Umbral calibrado**: 0.93 (ajustable en la interfaz)
|
| 27 |
+
|
| 28 |
+
## Uso
|
| 29 |
+
|
| 30 |
+
Ingresa los datos de una transacción y el modelo predice la probabilidad de fraude.
|
| 31 |
+
El umbral de decisión es ajustable según la tolerancia al riesgo.
|
| 32 |
+
|
| 33 |
+
## Links
|
| 34 |
+
|
| 35 |
+
- [Dataset](https://huggingface.co/datasets/alenc123/credit-card-fraud)
|
| 36 |
+
- [Modelo](https://huggingface.co/gusdelact/credit-card-fraud-xgboost)
|
app.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""app.py — App de inferencia para detección de fraude en tarjetas de crédito.
|
| 3 |
+
|
| 4 |
+
Descarga el modelo XGBoost desde HF Hub y expone una interfaz Gradio
|
| 5 |
+
para predecir si una transacción es fraudulenta.
|
| 6 |
+
|
| 7 |
+
Desplegada en Hugging Face Spaces.
|
| 8 |
+
"""
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import joblib
|
| 11 |
+
import numpy as np
|
| 12 |
+
import os
|
| 13 |
+
from huggingface_hub import hf_hub_download
|
| 14 |
+
|
| 15 |
+
# --- Configuración ---
|
| 16 |
+
MODEL_REPO = os.environ.get("HF_MODEL_REPO", "gusdelact/credit-card-fraud-xgboost")
|
| 17 |
+
OPTIMAL_THRESHOLD = 0.9306 # Calibrado con curva precision-recall
|
| 18 |
+
|
| 19 |
+
# Categorías de transacción disponibles
|
| 20 |
+
CATEGORIES = [
|
| 21 |
+
"entertainment", "food_dining", "gas_transport", "grocery_net",
|
| 22 |
+
"grocery_pos", "health_fitness", "home", "kids_pets",
|
| 23 |
+
"misc_net", "misc_pos", "personal_care", "shopping_net",
|
| 24 |
+
"shopping_pos", "travel"
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_model():
|
| 29 |
+
"""Descarga y carga el modelo desde HF Hub."""
|
| 30 |
+
print(f"Descargando modelo desde: {MODEL_REPO}")
|
| 31 |
+
model_path = hf_hub_download(MODEL_REPO, "model.joblib")
|
| 32 |
+
model = joblib.load(model_path)
|
| 33 |
+
print("✅ Modelo cargado correctamente")
|
| 34 |
+
return model
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Cargar modelo al iniciar
|
| 38 |
+
model = load_model()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build_feature_vector(amt, lat, long, city_pop, merch_lat, merch_long,
|
| 42 |
+
merch_zipcode, category, gender):
|
| 43 |
+
"""Construye el vector de features en el orden esperado por el modelo.
|
| 44 |
+
|
| 45 |
+
Features (23 total):
|
| 46 |
+
- 7 numéricas (estandarizadas): amt, lat, long, city_pop, merch_lat, merch_long, merch_zipcode
|
| 47 |
+
- 14 one-hot category: entertainment, food_dining, gas_transport, grocery_net,
|
| 48 |
+
grocery_pos, health_fitness, home, kids_pets, misc_net, misc_pos,
|
| 49 |
+
personal_care, shopping_net, shopping_pos, travel
|
| 50 |
+
- 2 one-hot gender: F, M
|
| 51 |
+
"""
|
| 52 |
+
# Numéricas (nota: en producción deberían pasar por el StandardScaler,
|
| 53 |
+
# pero para la demo usamos valores directos ya que el modelo fue entrenado
|
| 54 |
+
# con datos escalados)
|
| 55 |
+
features = [amt, lat, long, city_pop, merch_lat, merch_long, merch_zipcode]
|
| 56 |
+
|
| 57 |
+
# One-hot encoding de categoría
|
| 58 |
+
for cat in CATEGORIES:
|
| 59 |
+
features.append(1.0 if category == cat else 0.0)
|
| 60 |
+
|
| 61 |
+
# One-hot encoding de género
|
| 62 |
+
features.append(1.0 if gender == "F" else 0.0)
|
| 63 |
+
features.append(1.0 if gender == "M" else 0.0)
|
| 64 |
+
|
| 65 |
+
return np.array(features).reshape(1, -1)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def predict_fraud(amt, lat, long, city_pop, merch_lat, merch_long,
|
| 69 |
+
merch_zipcode, category, gender, threshold):
|
| 70 |
+
"""Predice si una transacción es fraudulenta."""
|
| 71 |
+
try:
|
| 72 |
+
X = build_feature_vector(
|
| 73 |
+
amt, lat, long, city_pop, merch_lat, merch_long,
|
| 74 |
+
merch_zipcode, category, gender
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
proba = model.predict_proba(X)[0, 1]
|
| 78 |
+
is_fraud = proba >= threshold
|
| 79 |
+
|
| 80 |
+
# Resultado formateado
|
| 81 |
+
result = {
|
| 82 |
+
"🚨 FRAUDE": float(proba),
|
| 83 |
+
"✅ Legítima": float(1 - proba),
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
detail = f"**Probabilidad de fraude: {proba:.4f}**\n\n"
|
| 87 |
+
detail += f"Umbral aplicado: {threshold:.4f}\n\n"
|
| 88 |
+
|
| 89 |
+
if is_fraud:
|
| 90 |
+
detail += "⚠️ **ALERTA: Transacción clasificada como FRAUDULENTA**\n\n"
|
| 91 |
+
detail += f"La probabilidad ({proba:.4f}) supera el umbral ({threshold:.4f})."
|
| 92 |
+
else:
|
| 93 |
+
detail += "✅ **Transacción clasificada como LEGÍTIMA**\n\n"
|
| 94 |
+
detail += f"La probabilidad ({proba:.4f}) está por debajo del umbral ({threshold:.4f})."
|
| 95 |
+
|
| 96 |
+
return result, detail
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
return {"Error": 1.0}, f"❌ Error: {str(e)}"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# --- Ejemplos predefinidos ---
|
| 103 |
+
examples = [
|
| 104 |
+
# Transacción legítima típica (monto bajo, gasolina)
|
| 105 |
+
[25.50, 38.0, -90.0, 50000, 38.1, -90.1, 63101, "gas_transport", "M", OPTIMAL_THRESHOLD],
|
| 106 |
+
# Transacción sospechosa (monto alto, entretenimiento)
|
| 107 |
+
[950.00, 40.7, -74.0, 8000000, 41.0, -73.5, 10001, "entertainment", "F", OPTIMAL_THRESHOLD],
|
| 108 |
+
# Compra online moderada
|
| 109 |
+
[150.00, 34.0, -118.2, 3900000, 34.1, -118.0, 90001, "shopping_net", "F", OPTIMAL_THRESHOLD],
|
| 110 |
+
# Transacción alta en viajes
|
| 111 |
+
[1200.00, 25.8, -80.2, 400000, 26.0, -80.0, 33101, "travel", "M", OPTIMAL_THRESHOLD],
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
# --- UI ---
|
| 115 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="🔍 Fraud Detector") as demo:
|
| 116 |
+
gr.Markdown("""
|
| 117 |
+
# 🔍 Credit Card Fraud Detector
|
| 118 |
+
|
| 119 |
+
Modelo XGBoost entrenado con SMOTE para detectar transacciones fraudulentas.
|
| 120 |
+
|
| 121 |
+
**Dataset**: [alenc123/credit-card-fraud](https://huggingface.co/datasets/alenc123/credit-card-fraud)
|
| 122 |
+
| **Modelo**: [gusdelact/credit-card-fraud-xgboost](https://huggingface.co/gusdelact/credit-card-fraud-xgboost)
|
| 123 |
+
""")
|
| 124 |
+
|
| 125 |
+
with gr.Tab("🔮 Predicción"):
|
| 126 |
+
with gr.Row():
|
| 127 |
+
with gr.Column(scale=2):
|
| 128 |
+
gr.Markdown("### Datos de la Transacción")
|
| 129 |
+
amt = gr.Number(label="Monto (USD)", value=100.0, minimum=1.0)
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
category = gr.Dropdown(
|
| 133 |
+
choices=CATEGORIES, value="grocery_pos",
|
| 134 |
+
label="Categoría"
|
| 135 |
+
)
|
| 136 |
+
gender = gr.Radio(choices=["M", "F"], value="M", label="Género")
|
| 137 |
+
|
| 138 |
+
gr.Markdown("### Ubicación del Titular")
|
| 139 |
+
with gr.Row():
|
| 140 |
+
lat = gr.Number(label="Latitud", value=38.0)
|
| 141 |
+
long = gr.Number(label="Longitud", value=-90.0)
|
| 142 |
+
city_pop = gr.Number(label="Población ciudad", value=50000)
|
| 143 |
+
|
| 144 |
+
gr.Markdown("### Ubicación del Comercio")
|
| 145 |
+
with gr.Row():
|
| 146 |
+
merch_lat = gr.Number(label="Latitud comercio", value=38.1)
|
| 147 |
+
merch_long = gr.Number(label="Longitud comercio", value=-90.1)
|
| 148 |
+
merch_zipcode = gr.Number(label="ZIP comercio", value=63101)
|
| 149 |
+
|
| 150 |
+
threshold = gr.Slider(
|
| 151 |
+
0.1, 0.99, value=OPTIMAL_THRESHOLD, step=0.01,
|
| 152 |
+
label="Umbral de decisión",
|
| 153 |
+
info="Calibrado en 0.93 para maximizar F1. Bajar para más sensibilidad."
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
predict_btn = gr.Button("🔍 Analizar Transacción", variant="primary", size="lg")
|
| 157 |
+
|
| 158 |
+
with gr.Column(scale=1):
|
| 159 |
+
gr.Markdown("### Resultado")
|
| 160 |
+
output_label = gr.Label(num_top_classes=2, label="Clasificación")
|
| 161 |
+
output_detail = gr.Markdown(label="Detalle")
|
| 162 |
+
|
| 163 |
+
predict_btn.click(
|
| 164 |
+
fn=predict_fraud,
|
| 165 |
+
inputs=[amt, lat, long, city_pop, merch_lat, merch_long,
|
| 166 |
+
merch_zipcode, category, gender, threshold],
|
| 167 |
+
outputs=[output_label, output_detail],
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
gr.Examples(
|
| 171 |
+
examples=examples,
|
| 172 |
+
inputs=[amt, lat, long, city_pop, merch_lat, merch_long,
|
| 173 |
+
merch_zipcode, category, gender, threshold],
|
| 174 |
+
outputs=[output_label, output_detail],
|
| 175 |
+
fn=predict_fraud,
|
| 176 |
+
cache_examples=False,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
with gr.Tab("📊 Info del Modelo"):
|
| 180 |
+
gr.Markdown(f"""
|
| 181 |
+
## Información del Modelo
|
| 182 |
+
|
| 183 |
+
| Aspecto | Detalle |
|
| 184 |
+
|---------|---------|
|
| 185 |
+
| **Tipo** | XGBClassifier |
|
| 186 |
+
| **Técnica de balanceo** | SMOTE (sampling_strategy=0.2) |
|
| 187 |
+
| **Features** | 23 (7 numéricas + 16 one-hot) |
|
| 188 |
+
| **ROC-AUC** | 0.9940 |
|
| 189 |
+
| **PR-AUC** | 0.7878 |
|
| 190 |
+
| **F1 (umbral calibrado)** | 0.7435 |
|
| 191 |
+
| **Umbral óptimo** | 0.9306 |
|
| 192 |
+
|
| 193 |
+
### Hiperparámetros (RandomizedSearchCV, CV=5)
|
| 194 |
+
|
| 195 |
+
| Parámetro | Valor |
|
| 196 |
+
|-----------|-------|
|
| 197 |
+
| max_depth | 6 |
|
| 198 |
+
| n_estimators | 250 |
|
| 199 |
+
| learning_rate | 0.1 |
|
| 200 |
+
| subsample | 0.8 |
|
| 201 |
+
| colsample_bytree | 0.6 |
|
| 202 |
+
| reg_alpha | 0.1 |
|
| 203 |
+
| reg_lambda | 1 |
|
| 204 |
+
| min_child_weight | 3 |
|
| 205 |
+
| tree_method | hist |
|
| 206 |
+
|
| 207 |
+
### Sobre el Umbral
|
| 208 |
+
|
| 209 |
+
El umbral por defecto (0.5) da un recall alto (85%) pero muchos falsos positivos.
|
| 210 |
+
El umbral calibrado (0.93) maximiza el F1-score, balanceando precision y recall.
|
| 211 |
+
|
| 212 |
+
- **Umbral bajo** → más transacciones marcadas como fraude (más seguro, más falsos positivos)
|
| 213 |
+
- **Umbral alto** → solo marca fraudes muy claros (menos alertas, puede dejar pasar fraudes)
|
| 214 |
+
|
| 215 |
+
### Dataset
|
| 216 |
+
|
| 217 |
+
[alenc123/credit-card-fraud](https://huggingface.co/datasets/alenc123/credit-card-fraud)
|
| 218 |
+
— 1.3M transacciones simuladas con 0.58% de fraude.
|
| 219 |
+
""")
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==6.14.0
|
| 2 |
+
xgboost==3.2.0
|
| 3 |
+
scikit-learn==1.8.0
|
| 4 |
+
numpy==2.4.5
|
| 5 |
+
joblib==1.5.3
|
| 6 |
+
huggingface-hub>=0.20.0
|