File size: 3,661 Bytes
0b46a56
8e0b5f1
 
 
a134096
cdc7ddc
ab22b96
 
 
 
 
a134096
 
8e0b5f1
 
 
 
 
cdc7ddc
ab22b96
 
 
 
 
 
 
 
 
 
 
 
 
 
a134096
8e0b5f1
a134096
4ffcd3e
cdc7ddc
8e0b5f1
cdc7ddc
92bcb5f
4ffcd3e
cdc7ddc
a134096
7ea262c
a134096
7ea262c
a134096
 
 
 
ab22b96
a134096
 
ab22b96
a134096
 
ab22b96
a134096
 
7ea262c
cdc7ddc
4ffcd3e
 
cdc7ddc
a134096
cdc7ddc
7ea262c
a134096
7ea262c
a134096
7ea262c
cdc7ddc
 
 
7ea262c
a134096
8e0b5f1
a134096
8e0b5f1
a134096
 
 
 
 
0b46a56
a134096
 
7ea262c
a134096
 
cdc7ddc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a134096
 
 
 
ab22b96
cdc7ddc
ab22b96
 
 
a134096
 
ab22b96
a134096
 
 
ab22b96
a134096
 
 
 
 
7ea262c
a134096
 
ab22b96
a134096
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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)