Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| import joblib | |
| from sklearn.ensemble import RandomForestClassifier | |
| from sklearn.preprocessing import StandardScaler | |
| # Load the dataset for feature extraction | |
| csv_file_path = "creditcard.csv" # Ensure this file is uploaded to Hugging Face | |
| df = pd.read_csv(csv_file_path) | |
| # Select important features | |
| selected_features = ["Amount", "V1", "V2", "V3", "Class"] | |
| df = df[selected_features] | |
| # Train-test split | |
| X = df.drop(columns=["Class"]) | |
| y = df["Class"] | |
| # Standardize "Amount" | |
| scaler = StandardScaler() | |
| X["Amount"] = scaler.fit_transform(X[["Amount"]]) | |
| # Train model | |
| model = RandomForestClassifier(n_estimators=100, random_state=42) | |
| model.fit(X, y) | |
| # Save model and scaler | |
| joblib.dump(model, "fraud_model.pkl") | |
| joblib.dump(scaler, "scaler.pkl") | |
| # Define function for prediction | |
| def predict_fraud(amount, v1, v2, v3): | |
| scaler = joblib.load("scaler.pkl") | |
| model = joblib.load("fraud_model.pkl") | |
| input_data = np.array([[amount, v1, v2, v3]]) | |
| input_data[:, 0] = scaler.transform(input_data[:, [0]]) # Scale amount | |
| prediction = model.predict(input_data) | |
| return "Fraudulent Transaction" if prediction[0] == 1 else "Non-Fraudulent Transaction" | |
| # Gradio UI | |
| iface = gr.Interface( | |
| fn=predict_fraud, | |
| inputs=[ | |
| gr.Number(label="Transaction Amount"), | |
| gr.Number(label="V1"), | |
| gr.Number(label="V2"), | |
| gr.Number(label="V3"), | |
| ], | |
| outputs="text", | |
| title="Credit Card Fraud Detection", | |
| description="Enter transaction details to check if it's fraudulent or not.", | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |