Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
289 lines (237 loc) · 10.5 KB
/
Copy pathapp.py
File metadata and controls
289 lines (237 loc) · 10.5 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
app.py
Streamlit dashboard for the Credit Card Fraud Anomaly Detection project.
IMPORTANT: This app NEVER retrains the model. It only loads the artifacts
already saved by train_model.py (models/isolation_forest_model.pkl and
models/evaluation_results.pkl).
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import streamlit as st
from sklearn.metrics import ConfusionMatrixDisplay
from preprocessing import COLUMNS_TO_SCALE
from utils import DATASET_PATH, EVAL_RESULTS_PATH, MODEL_PATH, load_artifact, model_exists
st.set_page_config(
page_title="Credit Card Fraud Anomaly Detection",
page_icon="💳",
layout="wide",
)
PAGES = [
"Home",
"Dataset Preview",
"Data Preprocessing Summary",
"Fraud Detection Results",
"Model Performance",
"Predict Transaction",
]
# ----------------------------------------------------------------------
# Cached loaders — the app only ever READS saved artifacts, never trains.
# ----------------------------------------------------------------------
@st.cache_resource
def get_model_bundle():
return load_artifact(MODEL_PATH)
@st.cache_resource
def get_eval_results():
return load_artifact(EVAL_RESULTS_PATH)
@st.cache_data
def get_dataset_sample(n_rows: int = 2000):
df = pd.read_csv(DATASET_PATH, nrows=n_rows)
return df
@st.cache_data
def get_full_class_counts():
# Only reads the 'Class' column so this stays fast even though the
# full dataset has ~285k rows.
df = pd.read_csv(DATASET_PATH, usecols=["Class"])
return df["Class"].value_counts()
# ----------------------------------------------------------------------
# Sidebar navigation
# ----------------------------------------------------------------------
st.sidebar.title("💳 Fraud Detection")
page = st.sidebar.radio("Navigate", PAGES)
if not model_exists():
st.error(
"No trained model found at `models/isolation_forest_model.pkl`.\n\n"
"Run `python train_model.py` first to train and save the model. "
"This app never trains a model itself."
)
st.stop()
# ----------------------------------------------------------------------
# 1. Home
# ----------------------------------------------------------------------
if page == "Home":
st.title("💳 Credit Card Fraud Anomaly Detection")
st.markdown(
"""
This dashboard presents an **unsupervised anomaly detection** system for
identifying fraudulent credit card transactions, built with an
**Isolation Forest** model.
### About the project
- **Dataset:** Real anonymized European credit card transactions
(Kaggle "Credit Card Fraud Detection" dataset, ULB), 284,807 transactions
collected over two days, with only 492 (0.172%) labeled fraudulent.
- **Model:** `IsolationForest` from scikit-learn — an unsupervised
algorithm that isolates anomalies rather than learning from labeled
examples.
- **Metrics reported:** Precision-Recall AUC and F1-Score for the
minority (fraud) class — the metrics that matter on a highly
imbalanced dataset.
### How to use this dashboard
Use the sidebar to explore:
1. **Dataset Preview** — a look at the raw data.
2. **Data Preprocessing Summary** — how features were prepared.
3. **Fraud Detection Results** — class distribution, confusion matrix, PR curve.
4. **Model Performance** — headline PR-AUC and F1 metrics.
5. **Predict Transaction** — score a transaction you enter manually.
> The model shown here was trained offline via `train_model.py` and is
> only *loaded* by this app — it is never retrained here.
"""
)
# ----------------------------------------------------------------------
# 2. Dataset Preview
# ----------------------------------------------------------------------
elif page == "Dataset Preview":
st.title("📊 Dataset Preview")
sample_df = get_dataset_sample(2000)
st.markdown(
"Preview of the raw dataset (`dataset/creditcard.csv`). "
"Showing the first 2,000 rows for performance; the full dataset "
"contains **284,807** transactions."
)
st.dataframe(sample_df.head(50), use_container_width=True)
col1, col2, col3 = st.columns(3)
col1.metric("Total transactions", "284,807")
col2.metric("Total features", sample_df.shape[1] - 1)
col3.metric("Fraud cases", "492 (0.172%)")
st.subheader("Column summary")
st.dataframe(sample_df.describe().T, use_container_width=True)
# ----------------------------------------------------------------------
# 3. Data Preprocessing Summary
# ----------------------------------------------------------------------
elif page == "Data Preprocessing Summary":
st.title("🧹 Data Preprocessing Summary")
bundle = get_model_bundle()
st.markdown(
"""
The preprocessing pipeline (`preprocessing.py`) performs the following steps:
1. **Stratified train/test split** (80% / 20%) — preserves the original
fraud ratio in both splits.
2. **Feature scaling** — `StandardScaler` fitted **only on the training
split** and applied to both splits, to avoid data leakage.
3. **No resampling / synthetic data** — the class imbalance is handled
entirely by the anomaly-detection approach and threshold tuning,
not by oversampling or undersampling.
"""
)
st.subheader("Columns scaled")
st.write(COLUMNS_TO_SCALE)
st.caption(
"V1–V28 are left untouched because they are already the output of a "
"PCA transformation performed by the original dataset authors."
)
st.subheader("Feature columns used by the model")
st.code(", ".join(bundle["feature_columns"]))
eval_results = get_eval_results()
col1, col2 = st.columns(2)
col1.metric("Training samples", f"{eval_results['n_train']:,}")
col2.metric("Test samples", f"{eval_results['n_test']:,}")
# ----------------------------------------------------------------------
# 4. Fraud Detection Results
# ----------------------------------------------------------------------
elif page == "Fraud Detection Results":
st.title("🚨 Fraud Detection Results")
eval_results = get_eval_results()
st.subheader("Fraud vs Normal Distribution")
class_counts = get_full_class_counts()
fig, ax = plt.subplots(figsize=(5, 4))
labels = ["Normal (0)", "Fraud (1)"]
values = [class_counts.get(0, 0), class_counts.get(1, 0)]
ax.bar(labels, values, color=["#4C72B0", "#C44E52"])
ax.set_ylabel("Number of transactions")
ax.set_title("Class Distribution (log scale)")
ax.set_yscale("log")
for i, v in enumerate(values):
ax.text(i, v, f"{v:,}", ha="center", va="bottom")
st.pyplot(fig)
st.subheader("Confusion Matrix (Test Set)")
cm = eval_results["confusion_matrix"]
fig2, ax2 = plt.subplots(figsize=(5, 4))
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=["Normal", "Fraud"])
disp.plot(ax=ax2, cmap="Blues", colorbar=False)
st.pyplot(fig2)
st.subheader("Precision-Recall Curve")
fig3, ax3 = plt.subplots(figsize=(6, 4.5))
ax3.plot(eval_results["recall_curve"], eval_results["precision_curve"], color="#C44E52")
ax3.set_xlabel("Recall")
ax3.set_ylabel("Precision")
ax3.set_title(f"Precision-Recall Curve (AUC = {eval_results['pr_auc']:.4f})")
ax3.grid(alpha=0.3)
st.pyplot(fig3)
# ----------------------------------------------------------------------
# 5. Model Performance
# ----------------------------------------------------------------------
elif page == "Model Performance":
st.title("📈 Model Performance")
eval_results = get_eval_results()
bundle = get_model_bundle()
col1, col2 = st.columns(2)
col1.metric("Precision-Recall AUC", f"{eval_results['pr_auc']:.4f}")
col2.metric("F1-Score (Fraud class)", f"{eval_results['f1_score']:.4f}")
st.subheader("Best hyperparameters (selected via PR-AUC search)")
st.json(eval_results["best_params"])
st.subheader("Decision threshold")
st.write(
f"Anomaly-score threshold used to flag fraud: "
f"**{eval_results['threshold']:.6f}** (selected to maximize F1-score "
f"on the test set)."
)
st.caption(
"Metrics are computed once during training (`train_model.py`) on a "
"held-out test set and simply displayed here — this app does not "
"recompute or retrain anything."
)
# ----------------------------------------------------------------------
# 6. Predict Transaction
# ----------------------------------------------------------------------
elif page == "Predict Transaction":
st.title("🔍 Predict Transaction")
st.markdown(
"Manually enter transaction feature values below, then click "
"**Predict** to classify the transaction as **Fraud** or **Normal** "
"using the saved Isolation Forest model."
)
bundle = get_model_bundle()
model = bundle["model"]
scaler = bundle["scaler"]
threshold = bundle["threshold"]
feature_columns = bundle["feature_columns"]
with st.form("predict_form"):
col1, col2 = st.columns(2)
with col1:
time_val = st.number_input("Time (seconds since first transaction)", value=0.0, step=1.0)
with col2:
amount_val = st.number_input("Amount", value=0.0, step=1.0, min_value=0.0)
st.markdown("**PCA features (V1–V28)**")
st.caption("These are anonymized/PCA-transformed features from the original dataset. Default is 0.0.")
v_values = {}
v_cols = [c for c in feature_columns if c.startswith("V")]
n_per_row = 4
for i in range(0, len(v_cols), n_per_row):
row_cols = st.columns(n_per_row)
for j, col_name in enumerate(v_cols[i : i + n_per_row]):
with row_cols[j]:
v_values[col_name] = st.number_input(col_name, value=0.0, format="%.4f", key=col_name)
submitted = st.form_submit_button("Predict")
if submitted:
raw_input = {"Time": time_val, "Amount": amount_val, **v_values}
input_df = pd.DataFrame([raw_input])[feature_columns]
scaled_input = input_df.copy()
scaled_input[COLUMNS_TO_SCALE] = scaler.transform(input_df[COLUMNS_TO_SCALE])
anomaly_score = -model.decision_function(scaled_input)[0]
is_fraud = anomaly_score >= threshold
st.divider()
if is_fraud:
st.error("### Result: **Fraud**")
else:
st.success("### Result: **Normal**")