Sakil's picture
Create app.py
da80cd0 verified
raw
history blame
2.07 kB
import gradio as gr
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import pickle
# Load the trained model
with open('knn_model.pkl', 'rb') as file:
kn_class = pickle.load(file)
# Load the fitted MinMaxScaler
with open('scaler.pkl', 'rb') as file:
scaler = pickle.load(file)
def predict_fraud(cc_num, gender, lat, long, city_pop, unix_time, amount):
# Handle categorical feature 'Gender'
gender = 1 if gender == 'M' else 0
# Scale the amount feature
amount_scaled = scaler.transform([[amount]])[0][0]
# Create input dataframe for the model
input_data = pd.DataFrame({
'cc_num': [cc_num],
'Gender': [gender],
'lat': [lat],
'long': [long],
'city_pop': [city_pop],
'unix_time': [unix_time],
'Amount_Scaled': [amount_scaled]
})
# Predict using the loaded model
prediction = kn_class.predict(input_data)
# Return the result
return 'Fraudulent Transaction' if prediction[0] == 1 else 'Legitimate Transaction'
# Define examples, including one example of fraud
examples = [
[1234567890123456, 'M', 40.712776, -74.005974, 8398748, 1614575732, 100.0], # Legitimate transaction
[2345678901234567, 'F', 34.052235, -118.243683, 3990456, 1614575832, 200.0], # Legitimate transaction
[3456789012345678, 'M', 37.774929, -122.419416, 883305, 1614575932, 5000.0] # Fraudulent transaction
]
# Define Gradio interface
interface = gr.Interface(
fn=predict_fraud,
inputs=[
gr.Number(label="Credit Card Number"),
gr.Radio(['M', 'F'], label="Gender"),
gr.Number(label="Latitude"),
gr.Number(label="Longitude"),
gr.Number(label="City Population"),
gr.Number(label="Unix Time"),
gr.Number(label="Transaction Amount")
],
outputs="text",
title="Fraud Detection Application",
description="Enter the transaction details to predict if it is fraudulent or legitimate.",
examples=examples
)
# Launch the interface
interface.launch()