Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from sklearn.model_selection import train_test_split
|
| 4 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 5 |
+
from sklearn.preprocessing import LabelEncoder
|
| 6 |
+
|
| 7 |
+
# Load dataset
|
| 8 |
+
df = pd.read_csv("fraud_data.csv")
|
| 9 |
+
|
| 10 |
+
# Preprocess data
|
| 11 |
+
le_country = LabelEncoder()
|
| 12 |
+
le_device = LabelEncoder()
|
| 13 |
+
df['country'] = le_country.fit_transform(df['country'])
|
| 14 |
+
df['device'] = le_device.fit_transform(df['device'])
|
| 15 |
+
|
| 16 |
+
# Convert transaction_time to minutes
|
| 17 |
+
df['transaction_time'] = df['transaction_time'].apply(lambda x: int(x.split(":")[0]) * 60 + int(x.split(":")[1]))
|
| 18 |
+
|
| 19 |
+
# Features and target
|
| 20 |
+
X = df.drop('is_fraud', axis=1)
|
| 21 |
+
y = df['is_fraud']
|
| 22 |
+
|
| 23 |
+
# Split data
|
| 24 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 25 |
+
|
| 26 |
+
# Train model
|
| 27 |
+
model = RandomForestClassifier()
|
| 28 |
+
model.fit(X_train, y_train)
|
| 29 |
+
|
| 30 |
+
# Prediction function
|
| 31 |
+
def predict_fraud(amount, country, device, transaction_time):
|
| 32 |
+
country_encoded = le_country.transform([country])[0]
|
| 33 |
+
device_encoded = le_device.transform([device])[0]
|
| 34 |
+
time_in_minutes = int(transaction_time.split(":")[0]) * 60 + int(transaction_time.split(":")[1])
|
| 35 |
+
input_data = [[amount, country_encoded, device_encoded, time_in_minutes]]
|
| 36 |
+
prediction = model.predict(input_data)[0]
|
| 37 |
+
return "Fraudulent" if prediction == 1 else "Legitimate"
|
| 38 |
+
|
| 39 |
+
# Gradio interface
|
| 40 |
+
countries = df['country'].unique()
|
| 41 |
+
devices = df['device'].unique()
|
| 42 |
+
|
| 43 |
+
iface = gr.Interface(
|
| 44 |
+
fn=predict_fraud,
|
| 45 |
+
inputs=[
|
| 46 |
+
gr.Number(label="Amount"),
|
| 47 |
+
gr.Dropdown(choices=le_country.classes_.tolist(), label="Country"),
|
| 48 |
+
gr.Dropdown(choices=le_device.classes_.tolist(), label="Device"),
|
| 49 |
+
gr.Textbox(label="Transaction Time (HH:MM)")
|
| 50 |
+
],
|
| 51 |
+
outputs="text",
|
| 52 |
+
title="Fraud Detection System",
|
| 53 |
+
description="Enter transaction details to predict if it's fraudulent."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
iface.launch()
|