import streamlit as st import numpy as np import joblib import os import matplotlib.pyplot as plt import pandas as pd from sklearn.metrics import ( ConfusionMatrixDisplay, RocCurveDisplay, roc_auc_score ) st.set_page_config(page_title="Credit Card Fraud Detection", layout="centered") BASE_DIR = os.path.dirname(__file__) MODEL_PATH = os.path.join(BASE_DIR, "model.pkl") model = joblib.load(MODEL_PATH) # ================= LOAD TEST DATA ================= X_test_path = os.path.join(BASE_DIR, "X_test.npy") y_test_path = os.path.join(BASE_DIR, "y_test.npy") if os.path.exists(X_test_path): X_test = np.load(X_test_path) y_test = np.load(y_test_path) y_prob = model.predict_proba(X_test)[:, 1] y_pred = model.predict(X_test) auc = roc_auc_score(y_test, y_prob) else: X_test, y_test, y_prob, y_pred, auc = None, None, None, None, None # ================= TITLE ================= st.title("💳 Credit Card Fraud Detection") st.markdown("Real-time fraud detection using Machine Learning.") threshold = st.slider("Fraud detection threshold", 0.0, 1.0, 0.5) # ================= TABS ================= tab1, tab2 = st.tabs(["🔍 Prediction", "📊 Model Insights"]) # ================= TAB 1 ================= with tab1: st.subheader("Transaction Input") if st.button("🎲 Generate Random Transaction"): time = np.random.randint(0, 172800) amount = np.random.uniform(1, 5000) pca_values = np.random.normal(0, 1, 28) else: col1, col2 = st.columns(2) with col1: time = st.number_input("Time", value=0) with col2: amount = st.number_input("Amount", value=0.0) st.info("V1–V28 are PCA-transformed anonymized features.") pca_values = [] with st.expander("PCA Features"): for i in range(28): pca_values.append(st.number_input(f"V{i+1}", value=0.0)) features = np.array([[time] + list(pca_values) + [amount]]) if st.button("Predict"): with st.spinner("Analyzing transaction..."): prob = model.predict_proba(features)[0][1] pred = int(prob >= threshold) st.markdown("## Result") col1, col2 = st.columns(2) with col1: if pred == 1: st.error("🚨 Fraudulent Transaction") else: st.success("✅ Legitimate Transaction") with col2: st.metric("Fraud Probability", f"{prob:.4f}") st.progress(prob) # Download report report = pd.DataFrame({ "Time": [time], "Amount": [amount], "Fraud Probability": [prob], "Prediction": [pred] }) st.download_button( "📥 Download prediction report", report.to_csv(index=False), "prediction.csv" ) # ================= TAB 2 ================= with tab2: st.subheader("Model Performance") if X_test is None: st.info("Upload X_test.npy and y_test.npy to enable insights.") else: st.metric("AUC", round(auc, 3)) fig, ax = plt.subplots() RocCurveDisplay.from_predictions(y_test, y_prob, ax=ax) st.pyplot(fig) fig2, ax2 = plt.subplots() ConfusionMatrixDisplay.from_predictions(y_test, y_pred, ax=ax2) st.pyplot(fig2) if hasattr(model, "feature_importances_"): st.subheader("Feature Importance") fig3, ax3 = plt.subplots() ax3.bar(range(len(model.feature_importances_)), model.feature_importances_) ax3.set_title("Feature Importance") st.pyplot(fig3)