File size: 2,083 Bytes
da80cd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9232a7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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(inline=False)