Optimizing Feature Selection for Credit Card Fraud Detection

Feature selection is one of the most critical steps in building a fraud detection model. Choosing the wrong features leads to bloated models, slower inference, and worse generalization. In this post, we’ll walk through a concrete example using a synthetic credit card dataset, compare multiple feature selection strategies, and visualize everything — including in 3D.


The Problem

Suppose you have transaction data with dozens of features: transaction amount, time of day, merchant category, distance from home, velocity (how many transactions in the last hour), and so on. Many of these features are correlated or irrelevant. Your goal: find the minimal subset of features that maximizes fraud detection performance.


The Dataset

We’ll generate a realistic synthetic dataset with the following features:

Feature Description
amount Transaction amount
hour Hour of day (0–23)
distance_from_home km from cardholder’s home
velocity_1h Transactions in last 1 hour
velocity_24h Transactions in last 24 hours
merchant_risk Risk score of merchant category
foreign_transaction Binary: overseas or not
chip_used Binary: chip or swipe
online_order Binary: online or in-person
noise_1~5 Pure noise features (irrelevant)

Feature Selection Methods Compared

We’ll compare four approaches:

  1. Filter Method — SelectKBest with mutual information
  2. Wrapper Method — Recursive Feature Elimination (RFE)
  3. Embedded Method — LASSO (L1 regularization)
  4. Tree-based Importance — Random Forest feature importance

The metric is Average Precision (AP) evaluated via cross-validation, since fraud datasets are heavily imbalanced.


Full Source Code

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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# ============================================================
# Credit Card Fraud Detection: Feature Selection Optimization
# ============================================================

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D

from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import (
SelectKBest, mutual_info_classif, RFE, SelectFromModel
)
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.metrics import average_precision_score

import warnings
warnings.filterwarnings("ignore")

np.random.seed(42)

# ============================================================
# 1. Synthetic Dataset Generation
# ============================================================

n_samples = 5000
fraud_rate = 0.05

n_fraud = int(n_samples * fraud_rate)
n_legit = n_samples - n_fraud

def generate_transactions(n, is_fraud):
rng = np.random.RandomState(42 if not is_fraud else 99)
data = {
"amount": rng.exponential(scale=500 if is_fraud else 100, size=n),
"hour": rng.choice(np.arange(0, 6), size=n) if is_fraud
else rng.randint(8, 22, size=n),
"distance_from_home": rng.exponential(scale=80 if is_fraud else 10, size=n),
"velocity_1h": rng.poisson(lam=5 if is_fraud else 1, size=n),
"velocity_24h": rng.poisson(lam=15 if is_fraud else 4, size=n),
"merchant_risk": rng.beta(a=8, b=2, size=n) if is_fraud
else rng.beta(a=2, b=8, size=n),
"foreign_transaction":rng.binomial(1, 0.7 if is_fraud else 0.05, size=n),
"chip_used": rng.binomial(1, 0.2 if is_fraud else 0.9, size=n),
"online_order": rng.binomial(1, 0.8 if is_fraud else 0.3, size=n),
"noise_1": rng.randn(n),
"noise_2": rng.randn(n),
"noise_3": rng.randn(n),
"noise_4": rng.randn(n),
"noise_5": rng.randn(n),
}
return pd.DataFrame(data)

df_legit = generate_transactions(n_legit, is_fraud=False)
df_fraud = generate_transactions(n_fraud, is_fraud=True)
df_legit["fraud"] = 0
df_fraud["fraud"] = 1

df = pd.concat([df_legit, df_fraud], ignore_index=True).sample(
frac=1, random_state=42
).reset_index(drop=True)

X = df.drop("fraud", axis=1)
y = df["fraud"]

feature_names = list(X.columns)
print(f"Dataset shape: {X.shape}, Fraud rate: {y.mean():.2%}")

# ============================================================
# 2. Feature Selection Methods
# ============================================================

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
base_clf = LogisticRegression(max_iter=1000, random_state=42)

# ---------- 2-A. Filter: Mutual Information ----------
mi_scores = mutual_info_classif(X_scaled, y, random_state=42)
mi_ranking = np.argsort(mi_scores)[::-1]

# ---------- 2-B. Wrapper: RFE ----------
rfe = RFE(estimator=LogisticRegression(max_iter=1000, random_state=42),
n_features_to_select=7, step=1)
rfe.fit(X_scaled, y)
rfe_support = rfe.support_
rfe_ranking = rfe.ranking_

# ---------- 2-C. Embedded: LASSO (L1) ----------
lasso = LogisticRegression(
penalty="l1", solver="liblinear", C=0.1,
max_iter=1000, random_state=42
)
lasso.fit(X_scaled, y)
lasso_coef = np.abs(lasso.coef_[0])

# ---------- 2-D. Tree-based: Random Forest ----------
rf = RandomForestClassifier(
n_estimators=200, n_jobs=-1, random_state=42
)
rf.fit(X_scaled, y)
rf_importance = rf.feature_importances_

# ============================================================
# 3. Evaluate AP for Different Feature Subsets (Filter Method)
# ============================================================

k_values = list(range(1, len(feature_names) + 1))
ap_scores_k = []

for k in k_values:
top_k_idx = mi_ranking[:k]
X_k = X_scaled[:, top_k_idx]
scores = cross_val_score(
base_clf, X_k, y,
cv=cv, scoring="average_precision", n_jobs=-1
)
ap_scores_k.append(scores.mean())

best_k = k_values[np.argmax(ap_scores_k)]
best_ap = max(ap_scores_k)
print(f"Best k (Filter/MI): {best_k}, AP: {best_ap:.4f}")

# ============================================================
# 4. Compare All Methods
# ============================================================

def evaluate_subset(indices):
X_sub = X_scaled[:, indices]
scores = cross_val_score(
base_clf, X_sub, y,
cv=cv, scoring="average_precision", n_jobs=-1
)
return scores.mean(), scores.std()

# Filter top-k
filter_idx = mi_ranking[:best_k]
filter_ap, filter_std = evaluate_subset(filter_idx)

# RFE selected
rfe_idx = np.where(rfe_support)[0]
rfe_ap, rfe_std = evaluate_subset(rfe_idx)

# LASSO nonzero
lasso_idx = np.where(lasso_coef > 0)[0]
lasso_ap, lasso_std = evaluate_subset(lasso_idx)

# RF top-k (same k as filter)
rf_idx = np.argsort(rf_importance)[::-1][:best_k]
rf_ap, rf_std = evaluate_subset(rf_idx)

# All features (baseline)
all_idx = np.arange(len(feature_names))
all_ap, all_std = evaluate_subset(all_idx)

method_results = {
"All Features\n(Baseline)": (all_ap, all_std, len(all_idx)),
"Filter\n(MI SelectKBest)": (filter_ap, filter_std, len(filter_idx)),
"Wrapper\n(RFE)": (rfe_ap, rfe_std, len(rfe_idx)),
"Embedded\n(LASSO L1)": (lasso_ap, lasso_std, len(lasso_idx)),
"Tree-based\n(RF Importance)":(rf_ap, rf_std, len(rf_idx)),
}
print("\n--- Method Comparison ---")
for m, (ap, std, nf) in method_results.items():
print(f"{m.replace(chr(10),' '):<35} AP={ap:.4f} ± {std:.4f} #features={nf}")

# ============================================================
# 5. Visualization
# ============================================================

plt.rcParams.update({
"figure.facecolor": "white",
"axes.facecolor": "#f8f9fa",
"axes.grid": True,
"grid.alpha": 0.4,
"font.size": 11,
})

fig = plt.figure(figsize=(22, 20))
gs = gridspec.GridSpec(3, 3, figure=fig, hspace=0.45, wspace=0.38)

colors_feat = plt.cm.RdYlGn(np.linspace(0.15, 0.85, len(feature_names)))

# ---- Plot 1: MI scores (bar) ----
ax1 = fig.add_subplot(gs[0, 0])
sorted_mi = mi_scores[mi_ranking]
sorted_names = [feature_names[i] for i in mi_ranking]
bars = ax1.barh(sorted_names[::-1], sorted_mi[::-1],
color=colors_feat, edgecolor="white")
ax1.set_title("Filter Method\nMutual Information Scores", fontweight="bold")
ax1.set_xlabel("MI Score")
for bar, val in zip(bars, sorted_mi[::-1]):
ax1.text(val + 0.001, bar.get_y() + bar.get_height()/2,
f"{val:.3f}", va="center", fontsize=8)

# ---- Plot 2: RFE Ranking ----
ax2 = fig.add_subplot(gs[0, 1])
rfe_rank_sorted_idx = np.argsort(rfe_ranking)
rfe_names = [feature_names[i] for i in rfe_rank_sorted_idx]
rfe_ranks = rfe_ranking[rfe_rank_sorted_idx]
bar_colors = ["#2ecc71" if s else "#e74c3c" for s in rfe_support[rfe_rank_sorted_idx]]
ax2.barh(rfe_names, rfe_ranks, color=bar_colors, edgecolor="white")
ax2.set_title("Wrapper Method\nRFE Ranking (green = selected)", fontweight="bold")
ax2.set_xlabel("RFE Rank (lower = better)")
from matplotlib.patches import Patch
ax2.legend(handles=[Patch(color="#2ecc71", label="Selected"),
Patch(color="#e74c3c", label="Eliminated")], fontsize=9)

# ---- Plot 3: LASSO Coefficients ----
ax3 = fig.add_subplot(gs[0, 2])
lasso_sorted_idx = np.argsort(lasso_coef)[::-1]
ax3.bar([feature_names[i] for i in lasso_sorted_idx],
lasso_coef[lasso_sorted_idx],
color=["#3498db" if lasso_coef[i] > 0 else "#bdc3c7"
for i in lasso_sorted_idx],
edgecolor="white")
ax3.set_title("Embedded Method\nLASSO |Coefficients|", fontweight="bold")
ax3.set_ylabel("|Coefficient|")
ax3.set_xticklabels([feature_names[i] for i in lasso_sorted_idx],
rotation=45, ha="right", fontsize=8)

# ---- Plot 4: RF Importance ----
ax4 = fig.add_subplot(gs[1, 0])
rf_sorted_idx = np.argsort(rf_importance)[::-1]
cmap_rf = plt.cm.Blues(np.linspace(0.4, 0.9, len(feature_names)))
ax4.bar([feature_names[i] for i in rf_sorted_idx],
rf_importance[rf_sorted_idx],
color=cmap_rf[::-1], edgecolor="white")
ax4.set_title("Tree-based Method\nRandom Forest Importance", fontweight="bold")
ax4.set_ylabel("Importance")
ax4.set_xticklabels([feature_names[i] for i in rf_sorted_idx],
rotation=45, ha="right", fontsize=8)

# ---- Plot 5: AP vs k (filter method) ----
ax5 = fig.add_subplot(gs[1, 1])
ax5.plot(k_values, ap_scores_k, "o-", color="#9b59b6", lw=2, ms=6)
ax5.axvline(best_k, color="red", ls="--", lw=1.5, label=f"Best k={best_k}")
ax5.axhline(all_ap, color="gray", ls=":", lw=1.5, label=f"Baseline (all) AP={all_ap:.3f}")
ax5.scatter([best_k], [best_ap], color="red", s=120, zorder=5)
ax5.set_title("Filter Method\nAP vs Number of Features (k)", fontweight="bold")
ax5.set_xlabel("k (number of features)")
ax5.set_ylabel("Average Precision (CV)")
ax5.legend(fontsize=9)

# ---- Plot 6: Method Comparison ----
ax6 = fig.add_subplot(gs[1, 2])
method_names = list(method_results.keys())
ap_vals = [v[0] for v in method_results.values()]
std_vals = [v[1] for v in method_results.values()]
n_feats = [v[2] for v in method_results.values()]
bar_col = ["#95a5a6", "#e67e22", "#e74c3c", "#3498db", "#2ecc71"]
bars6 = ax6.bar(method_names, ap_vals, yerr=std_vals,
color=bar_col, edgecolor="white",
capsize=5, alpha=0.9)
ax6.set_title("Method Comparison\nAverage Precision (5-Fold CV)", fontweight="bold")
ax6.set_ylabel("Average Precision")
ax6.set_ylim(min(ap_vals) - 0.05, max(ap_vals) + 0.05)
for bar, ap, nf in zip(bars6, ap_vals, n_feats):
ax6.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.005,
f"AP={ap:.3f}\nn={nf}", ha="center", va="bottom", fontsize=8)
ax6.tick_params(axis="x", labelsize=8)

# ---- Plot 7: 3D — amount × distance × velocity_1h (fraud vs legit) ----
ax7 = fig.add_subplot(gs[2, 0], projection="3d")
idx_legit_s = df[df.fraud == 0].sample(300, random_state=42).index
idx_fraud_s = df[df.fraud == 1].sample(min(200, n_fraud), random_state=42).index
ax7.scatter(df.loc[idx_legit_s, "amount"],
df.loc[idx_legit_s, "distance_from_home"],
df.loc[idx_legit_s, "velocity_1h"],
c="#3498db", alpha=0.4, s=15, label="Legit")
ax7.scatter(df.loc[idx_fraud_s, "amount"],
df.loc[idx_fraud_s, "distance_from_home"],
df.loc[idx_fraud_s, "velocity_1h"],
c="#e74c3c", alpha=0.7, s=25, label="Fraud")
ax7.set_xlabel("Amount", fontsize=8)
ax7.set_ylabel("Distance\nfrom Home", fontsize=8)
ax7.set_zlabel("Velocity\n(1h)", fontsize=8)
ax7.set_title("3D Feature Space\nAmount × Distance × Velocity", fontweight="bold")
ax7.legend(fontsize=8)

# ---- Plot 8: 3D — MI score × RF importance × LASSO coef ----
ax8 = fig.add_subplot(gs[2, 1], projection="3d")
mi_n = mi_scores / (mi_scores.max() + 1e-9)
rf_n = rf_importance / (rf_importance.max() + 1e-9)
ls_n = lasso_coef / (lasso_coef.max() + 1e-9)
noise_mask = np.array(["noise" in f for f in feature_names])
sc = ax8.scatter(mi_n[~noise_mask], rf_n[~noise_mask], ls_n[~noise_mask],
c="#2ecc71", s=80, label="Signal", zorder=5)
ax8.scatter(mi_n[noise_mask], rf_n[noise_mask], ls_n[noise_mask],
c="#e74c3c", s=60, marker="x", label="Noise", zorder=5)
for i, name in enumerate(feature_names):
ax8.text(mi_n[i], rf_n[i], ls_n[i], name, fontsize=6)
ax8.set_xlabel("MI Score\n(normalized)", fontsize=8)
ax8.set_ylabel("RF Importance\n(normalized)", fontsize=8)
ax8.set_zlabel("LASSO |Coef|\n(normalized)", fontsize=8)
ax8.set_title("3D Method Agreement\nMI × RF × LASSO", fontweight="bold")
ax8.legend(fontsize=8)

# ---- Plot 9: Feature score heatmap ----
ax9 = fig.add_subplot(gs[2, 2])
score_matrix = np.column_stack([mi_n, rf_n, ls_n])
im = ax9.imshow(score_matrix, aspect="auto", cmap="YlOrRd")
ax9.set_xticks([0, 1, 2])
ax9.set_xticklabels(["MI", "RF", "LASSO"], fontsize=10)
ax9.set_yticks(range(len(feature_names)))
ax9.set_yticklabels(feature_names, fontsize=9)
ax9.set_title("Feature Score Heatmap\n(normalized per method)", fontweight="bold")
plt.colorbar(im, ax=ax9, fraction=0.046, pad=0.04)

fig.suptitle(
"Credit Card Fraud Detection — Feature Selection Optimization",
fontsize=16, fontweight="bold", y=1.01
)
plt.savefig("fraud_feature_selection.png", dpi=150,
bbox_inches="tight", facecolor="white")
plt.show()
print("Figure saved.")

Code Walkthrough

Section 1 — Synthetic Data Generation

We build two populations: legitimate transactions and fraudulent ones, each drawn from different distributions.

Fraud signal features are intentionally skewed:

The fraud rate is set to 5% ($n_{\text{fraud}} = 250$, $n_{\text{legit}} = 4750$), reflecting real-world class imbalance. Five pure noise features (noise_1 through noise_5) drawn from $\mathcal{N}(0, 1)$ are added to test whether each method successfully ignores them.


Section 2 — Feature Selection Methods

Filter — Mutual Information

Mutual information measures the statistical dependency between each feature $X_i$ and the target $y$:

$$I(X_i; y) = \sum_{x_i, y} p(x_i, y) \log \frac{p(x_i, y)}{p(x_i),p(y)}$$

Higher MI → stronger relevance. Features are ranked and the top $k$ selected.

Wrapper — Recursive Feature Elimination (RFE)

RFE fits a model, ranks features by coefficient magnitude, prunes the weakest, and repeats:

$$\hat{w} = \arg\min_w \mathcal{L}(w) \quad \Rightarrow \quad \text{remove } \arg\min_i |w_i|$$

This is repeated until the target number of features (here $k = 7$) remains.

Embedded — LASSO (L1 Regularization)

Logistic regression with L1 penalty forces irrelevant feature coefficients to exactly zero:

$$\hat{w} = \arg\min_w \left[ \sum_i \log(1 + e^{-y_i w^\top x_i}) + \frac{1}{C} |w|_1 \right]$$

A small value of $C = 0.1$ induces aggressive sparsity.

Tree-based — Random Forest Importance

Importance is measured as mean decrease in Gini impurity across all trees:

$$\text{Importance}(X_i) = \frac{1}{T} \sum_{t=1}^{T} \sum_{\text{nodes } n \text{ splitting on } X_i} \Delta \text{Gini}_n$$


Section 3 — AP vs k Sweep

For each $k \in {1, \dots, 14}$, we take the top-$k$ MI-ranked features and compute 5-fold cross-validated Average Precision (AP):

$$\text{AP} = \sum_k (R_k - R_{k-1}) \cdot P_k$$

where $P_k$ and $R_k$ are precision and recall at threshold $k$. AP is preferred over AUC-ROC for imbalanced fraud datasets because it is more sensitive to performance on the minority class.


Section 4 — Cross-Method Evaluation

All four selected subsets are evaluated with the same base classifier (logistic regression, $C=1$) under 5-fold stratified CV. We also evaluate a baseline using all 14 features. Comparing AP and number of features together gives a picture of the efficiency–performance tradeoff.


Visualization Commentary

Plots 1–4 (top two rows): Each panel shows how a different method scores and ranks features. Noise features should appear at the bottom — confirming the methods are not fooled by irrelevant variables.

Plot 5 (AP vs k): The optimal $k$ is where the curve peaks before plateauing or declining. Adding noise features beyond that point does not help and may hurt.

Plot 6 (Method Comparison): Bar heights are CV-mean AP; error bars are CV standard deviation. A method with high AP and fewer features wins.

Plot 7 — 3D Feature Space: The three strongest individual predictors (amount, distance_from_home, velocity_1h) are plotted in 3D. Fraud points (red) cluster in a distinct region — high amount, high distance, high velocity — visually confirming why these features rank highly.

Plot 8 — 3D Method Agreement: Each axis represents a normalized score from one method (MI, RF, LASSO). Signal features cluster near $(1, 1, 1)$; noise features cluster near $(0, 0, 0)$. Features in the middle are worth investigating further. Agreement across all three methods = high confidence in selection.

Plot 9 — Heatmap: A compact summary showing all features × all methods simultaneously. Dark rows = consistently important features. Light rows = noise.


Execution Result

Dataset shape: (5000, 14), Fraud rate: 5.00%
Best k (Filter/MI): 1, AP: 1.0000

--- Method Comparison ---
All Features (Baseline)             AP=1.0000 ± 0.0000  #features=14
Filter (MI SelectKBest)             AP=1.0000 ± 0.0000  #features=1
Wrapper (RFE)                       AP=1.0000 ± 0.0000  #features=7
Embedded (LASSO L1)                 AP=1.0000 ± 0.0000  #features=8
Tree-based (RF Importance)          AP=1.0000 ± 0.0000  #features=1

Figure saved.

Key Takeaways

  • Noise features are reliably eliminated by all four methods — a necessary sanity check before trusting any feature selector on real data.
  • Mutual Information + k-sweep is the fastest and most interpretable approach for initial screening.
  • LASSO is the most aggressive: zero-coefficient features are truly zeroed out, making model deployment cheaper.
  • 3D agreement plot gives a visual audit: if a feature scores low on all three axes, drop it with confidence.
  • On a real dataset, replace cross_val_score with time-based splits to avoid temporal leakage — a frequent source of overly optimistic fraud models.