File size: 2,460 Bytes
3806caf
46c5a60
 
 
 
 
 
 
 
 
578cae3
46c5a60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3806caf
46c5a60
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
import streamlit as st
import pandas as pd
import joblib

st.set_page_config(page_title="Payment Fraud Detection", page_icon="💳", layout="centered")

@st.cache_resource
def load_artifacts():
    model = joblib.load("src/randomforest_model.pkl")
    try:
        features = joblib.load("src/model_features.pkl")
    except Exception:
        features = None
    return model, features

model, model_features = load_artifacts()

st.title("💳 Payment Fraud Detection")
st.write("Enter transaction details and get a fraud prediction (0 = Not Fraud, 1 = Fraud).")

with st.sidebar:
    st.header("ℹ️ Info")
    st.write("**Model:** Random Forest")
    if model_features is None:
        st.warning("`model_features.pkl` not found. App will try to predict without reindexing columns.")
    else:
        st.caption(f"Loaded {len(model_features)} feature columns.")

st.subheader("Transaction Input")

col1, col2 = st.columns(2)
with col1:
    accountAgeDays = st.number_input("accountAgeDays", min_value=0, value=30, step=1)
    numItems = st.number_input("numItems", min_value=1, value=1, step=1)
with col2:
    localTime = st.number_input("localTime (e.g., 0–24)", min_value=0.0, value=12.0, step=0.5)
    paymentMethodAgeDays = st.number_input("paymentMethodAgeDays", min_value=0, value=10, step=1)

paymentMethod = st.selectbox("paymentMethod", ["paypal", "creditcard", "storecredit"])

if st.button("Predict", type="primary"):
    # Build one-row dataframe exactly like training input BEFORE get_dummies
    input_df = pd.DataFrame([{
        "accountAgeDays": accountAgeDays,
        "numItems": numItems,
        "localTime": localTime,
        "paymentMethodAgeDays": paymentMethodAgeDays,
        "paymentMethod": paymentMethod
    }])

    # One-hot encode like training
    X = pd.get_dummies(input_df, drop_first=True)

    # Align columns to training columns (important!)
    if model_features is not None:
        X = X.reindex(columns=model_features, fill_value=0)

    # Predict
    pred = model.predict(X)[0]
    proba = None
    if hasattr(model, "predict_proba"):
        proba = model.predict_proba(X)[0][1]

    st.divider()
    if pred == 1:
        st.error("🚨 Prediction: FRAUD (1)")
    else:
        st.success("✅ Prediction: NOT FRAUD (0)")

    if proba is not None:
        st.metric("Fraud Probability", f"{proba:.2%}")

    st.caption("Tip: If you get column mismatch issues, create `model_features.pkl` (see README).")