<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emma Wei on Medium]]></title>
        <description><![CDATA[Stories by Emma Wei on Medium]]></description>
        <link>https://medium.com/@yfwei0225?source=rss-33009d208c57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FSsQOmLOoWk3SFsY</url>
            <title>Stories by Emma Wei on Medium</title>
            <link>https://medium.com/@yfwei0225?source=rss-33009d208c57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:37:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yfwei0225/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Can Attention Beat XGBoost on Fraud Detection?]]></title>
            <link>https://medium.com/@yfwei0225/can-attention-beat-xgboost-on-fraud-detection-7cbf96b0836d?source=rss-33009d208c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cbf96b0836d</guid>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <dc:creator><![CDATA[Emma Wei]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 02:14:11 GMT</pubDate>
            <atom:updated>2026-06-16T02:55:14.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*PeqLD9XvdX7k-DSajWtb2g.png" /></figure><p><em>Tags: Transformer · TabTransformer · FT-Transformer · XGBoost · LSTM · Fraud Detection · Python · Imbalanced Data</em></p><blockquote><em>XGBoost remains the king of tabular data for most financial applications. But when your data has sequential structure — transaction histories, behavioural patterns over time — Transformers close the gap fast, and sometimes win. This article shows you exactly when, why, and how to run the comparison yourself.</em></blockquote><h3>Introduction</h3><p>There is a running joke in machine learning: “Have you tried XGBoost?” It gets asked at every Kaggle competition, every fintech hackathon, every credit risk review — and for good reason. Gradient-boosted trees have dominated tabular data for the better part of a decade. Fast, robust, interpretable, no preprocessing required.</p><p>Then came Transformers.</p><p>Originally built for natural language, the attention mechanism has proven stubbornly adaptable. Vision Transformers beat CNNs. Time-series Transformers rival LSTMs. And now TabTransformer and FT-Transformer are making a case for tabular data — XGBoost’s home turf.</p><p>The question every fraud analyst should be asking is not “what is a Transformer?” but “does it actually beat XGBoost on my data, and by how much?”</p><p>This article answers that question. We build a synthetic fraud detection dataset with realistic transaction sequences, implement five models (Logistic Regression, XGBoost, LSTM, TabTransformer, FT-Transformer), evaluate them on the full suite of metrics that matter in financial applications (AUC, PR-AUC, BSS, calibration), and draw practical conclusions about when to reach for each.</p><blockquote>Fraud detection is the ideal battleground: severe class imbalance (~1% fraud rate), mixed feature types (categorical + numerical), and sequential structure (transaction history) — conditions where Transformers are theoretically strongest.</blockquote><h3>Setting Up: Our Synthetic Fraud Dataset</h3><p>This article answers that question on a realistic setting: account takeover (ATO) fraud, 500,000 transactions, 1% fraud rate, account-based train/test split, and honest calibration throughout. No leakage. No isotonic artifacts.</p><p>We simulate a pure ATO attack pattern — the most common fraud type in digital banking. The attacker follows a three-phase state machine:</p><p>NORMAL → PROBING → FRAUD → DORMANT</p><p>Why this matters for model design: No single feature catches ATO. The fraud amount is elevated — but so are some legitimate purchases. The merchant is unusual — but accounts do visit new merchants. The signal is <em>joint</em>: amount AND merchant AND hour AND foreign, read together across the account’s recent history. This is exactly where attention and sequential models should have an advantage over flat tabular models.</p><p>Fraud phase: Large transactions (1.9× normal amount) at unusual merchants, 70% outside the account’s home category, elevated foreign activity, shifted to unusual hours.</p><pre>import numpy as np<br>import pandas as pd<br><br>np.random.seed(42)<br>rng = np.random.RandomState(42)<br><br>N_ACCOUNTS = 5_200<br>AVG_TXN    = 100<br><br>MERCHANT_CATS = [&quot;grocery&quot;,&quot;electronics&quot;,&quot;travel&quot;,&quot;food&quot;,<br>                 &quot;entertainment&quot;,&quot;gas&quot;,&quot;retail&quot;,&quot;online&quot;]<br>CHANNELS      = [&quot;web&quot;,&quot;mobile&quot;,&quot;pos&quot;,&quot;atm&quot;]<br>COUNTRIES     = [&quot;US&quot;,&quot;CA&quot;,&quot;GB&quot;,&quot;DE&quot;,&quot;FR&quot;,&quot;MX&quot;,&quot;CN&quot;,&quot;BR&quot;]<br><br>NORMAL=0; PROBING=1; FRAUD=2; DORMANT=3<br><br>acct_avg_amt  = rng.lognormal(4.0, 0.8, N_ACCOUNTS)<br>acct_avg_hour = rng.uniform(8, 21,  N_ACCOUNTS)<br>acct_home_cat = rng.randint(0, len(MERCHANT_CATS), N_ACCOUNTS)<br>acct_risk     = rng.beta(2, 10, N_ACCOUNTS)<br><br>records = []<br><br>for aid in range(N_ACCOUNTS):<br>    n_txns    = rng.poisson(AVG_TXN)<br>    state     = NORMAL<br>    t         = 0.0<br>    avg_amt   = acct_avg_amt[aid]<br>    avg_hr    = acct_avg_hour[aid]<br>    hcat      = acct_home_cat[aid]<br>    base_risk = acct_risk[aid]<br><br>    for seq in range(max(n_txns, 1)):<br><br>        r = rng.rand()<br>        if state == NORMAL:<br>            if r &lt; 0.006 * (1 + base_risk):<br>                state = PROBING<br>        elif state == PROBING:<br>            if r &lt; 0.18:<br>                state = FRAUD<br>        elif state == FRAUD:<br>            if r &lt; 0.45:<br>                state = DORMANT<br>        elif state == DORMANT:<br>            if r &lt; 0.04:<br>                state = NORMAL<br><br>        dt = rng.exponential(2.0)<br>        t += dt<br><br>        if state == NORMAL:<br>            amt  = rng.lognormal(np.log(avg_amt), 0.8)<br>            amt *= rng.lognormal(0, 0.10)                              # noise<br>            hr   = float(np.clip(rng.normal(avg_hr, 4.5), 0, 23))<br>            mcat = int(rng.choice(len(MERCHANT_CATS),<br>                       p=[0.60 if i==hcat else 0.40/7 for i in range(8)]))<br>            cntry= int(rng.choice(len(COUNTRIES),<br>                       p=[0.92 if i==0 else 0.08/7 for i in range(8)]))<br>            chan = int(rng.choice(len(CHANNELS), p=[0.22, 0.46, 0.20, 0.12]))<br><br>        elif state == PROBING:<br>            amt  = rng.lognormal(np.log(max(avg_amt * 0.70, 2.0)), 0.8)<br>            amt *= rng.lognormal(0, 0.10)                              # noise<br>            hr   = float(np.clip(rng.normal(avg_hr, 4.5), 0, 23))<br>            mcat = int(rng.choice(len(MERCHANT_CATS),<br>                       p=[0.45 if i==hcat else 0.55/7 for i in range(8)]))<br>            cntry= int(rng.choice(len(COUNTRIES),<br>                       p=[0.92 if i==0 else 0.08/7 for i in range(8)]))<br>            chan = int(rng.choice(len(CHANNELS), p=[0.22, 0.46, 0.20, 0.12]))<br><br>        elif state == FRAUD:<br>            amt  = rng.lognormal(np.log(avg_amt * 1.9), 0.8)<br>            amt *= rng.lognormal(0, 0.10)                              # noise<br>            hr   = float(np.clip(rng.normal(avg_hr + 2.0, 4.5), 0, 23))<br>            mcat = int(rng.choice(len(MERCHANT_CATS),<br>                       p=[0.30 if i==hcat else 0.70/7 for i in range(8)]))<br>            cntry= int(rng.choice(len(COUNTRIES),<br>                       p=[0.80 if i==0 else 0.20/7 for i in range(8)]))<br>            chan = int(rng.choice(len(CHANNELS), p=[0.18, 0.42, 0.25, 0.15]))<br><br>        else:  # DORMANT — realistic: mostly home but not always<br>            amt  = rng.lognormal(np.log(max(avg_amt * 0.3, 1)), 0.6)<br>            amt *= rng.lognormal(0, 0.10)                              # noise<br>            hr   = float(np.clip(rng.normal(avg_hr, 4.5), 0, 23))<br>            mcat = int(rng.choice(len(MERCHANT_CATS),<br>                       p=[0.80 if i==hcat else 0.20/7 for i in range(8)]))  # 80% home<br>            cntry= int(rng.choice(len(COUNTRIES),<br>                       p=[0.97 if i==0 else 0.03/7 for i in range(8)]))     # 3% foreign<br>            chan = int(rng.choice(len(CHANNELS), p=[0.22, 0.46, 0.20, 0.12]))<br><br>        records.append({<br>            &quot;account_id&quot;  : aid,<br>            &quot;txn_seq&quot;     : seq,<br>            &quot;timestamp&quot;   : round(t, 4),<br>            &quot;txn_amount&quot;  : round(float(amt), 2),<br>            &quot;hour_of_day&quot; : round(hr, 1),<br>            &quot;merchant_cat&quot;: MERCHANT_CATS[mcat],<br>            &quot;channel&quot;     : CHANNELS[chan],<br>            &quot;country&quot;     : COUNTRIES[cntry],<br>            &quot;account_age&quot; : round(t, 2),<br>            &quot;_state&quot;      : state,<br>            &quot;fraud&quot;       : int(state == FRAUD),<br>        })<br><br>df = pd.DataFrame(records).sort_values([&quot;account_id&quot;,&quot;timestamp&quot;]).reset_index(drop=True)<br><br>TARGET_TOTAL = 500_000<br>TARGET_FRAUD = 5_000<br>TARGET_LEGIT = TARGET_TOTAL - TARGET_FRAUD<br><br>fraud_idx = df[df[&quot;fraud&quot;] == 1].index.tolist()<br>legit_idx = df[df[&quot;fraud&quot;] == 0].index.tolist()<br><br>assert len(fraud_idx) &gt;= TARGET_FRAUD, f&quot;Not enough fraud: {len(fraud_idx)}&quot;<br>assert len(legit_idx) &gt;= TARGET_LEGIT, f&quot;Not enough legit: {len(legit_idx)}&quot;<br><br>keep_fraud = rng.choice(fraud_idx, size=TARGET_FRAUD, replace=False)<br>keep_legit = rng.choice(legit_idx, size=TARGET_LEGIT, replace=False)<br><br>df = (df.loc[list(keep_fraud) + list(keep_legit)]<br>        .sort_values([&quot;account_id&quot;, &quot;timestamp&quot;])<br>        .reset_index(drop=True))<br><br>assert len(df) == TARGET_TOTAL<br>assert df[&quot;fraud&quot;].sum() == TARGET_FRAUD<br><br># ── Features ───────────────────────────────────────────────────────────<br>g = df.groupby(&quot;account_id&quot;)<br><br>df[&quot;days_since_last&quot;]    = g[&quot;timestamp&quot;].diff().fillna(2.0)<br>df[&quot;velocity_1h&quot;]        = 1.0 / df[&quot;days_since_last&quot;].clip(lower=0.001)<br><br>acct_mean = g[&quot;txn_amount&quot;].transform(&quot;mean&quot;)<br>acct_std  = g[&quot;txn_amount&quot;].transform(&quot;std&quot;).fillna(1).clip(lower=1)<br>df[&quot;amount_z_score&quot;]     = (df[&quot;txn_amount&quot;] - acct_mean) / acct_std<br>df[&quot;amount_acct_ratio&quot;]  = (df[&quot;txn_amount&quot;] / acct_mean.clip(lower=1)).clip(upper=20)<br><br>acct_mean_hr = g[&quot;hour_of_day&quot;].transform(&quot;mean&quot;)<br>df[&quot;hour_deviation&quot;]     = (df[&quot;hour_of_day&quot;] - acct_mean_hr).abs()<br><br>acct_mode_cat = g[&quot;merchant_cat&quot;].transform(lambda x: x.mode().iloc[0])<br>df[&quot;is_unusual_merchant&quot;]= (df[&quot;merchant_cat&quot;] != acct_mode_cat).astype(float)<br>df[&quot;is_foreign&quot;]         = (df[&quot;country&quot;] != &quot;US&quot;).astype(float)<br><br># ── Encode ─────────────────────────────────────────────────────────────<br>df[&quot;merchant_cat&quot;] = pd.Categorical(df[&quot;merchant_cat&quot;], categories=MERCHANT_CATS)<br>df[&quot;channel&quot;]      = pd.Categorical(df[&quot;channel&quot;],      categories=CHANNELS)<br>df[&quot;country&quot;]      = pd.Categorical(df[&quot;country&quot;],      categories=COUNTRIES)<br><br># ── Train / test split (account-based) ────────────────────────────────<br>all_accts   = df[&quot;account_id&quot;].unique()<br>train_accts = set(rng.choice(all_accts, size=int(0.8*len(all_accts)), replace=False))<br>is_train    = df[&quot;account_id&quot;].isin(train_accts)<br>df_train, df_test = df[is_train].copy(), df[~is_train].copy()<br><br>NUM_COLS = [&quot;txn_amount&quot;,&quot;hour_of_day&quot;,&quot;days_since_last&quot;,&quot;velocity_1h&quot;,<br>            &quot;account_age&quot;,&quot;amount_acct_ratio&quot;,&quot;amount_z_score&quot;,<br>            &quot;hour_deviation&quot;,&quot;is_unusual_merchant&quot;,&quot;is_foreign&quot;]<br>CAT_COLS = [&quot;merchant_cat&quot;,&quot;channel&quot;,&quot;country&quot;]<br><br># ── Summary ────────────────────────────────────────────────────────────<br>total, frauds = len(df), df[&quot;fraud&quot;].sum()<br>print(f&quot;Dataset : {total:,} | Frauds: {frauds:,} ({frauds/total*100:.2f}%)&quot;)<br>print(f&quot;Train   : {len(df_train):,} | Test: {len(df_test):,}&quot;)<br><br>print(f&quot;\nSignal separation:&quot;)<br>fraud_df  = df[df[&quot;fraud&quot;] == 1]<br>normal_df = df[df[&quot;_state&quot;] == NORMAL]<br>dims = [<br>    (&quot;amount_acct_ratio&gt;1.8&quot;,<br>     (normal_df[&quot;amount_acct_ratio&quot;] &gt; 1.8).mean()*100,<br>     (fraud_df[&quot;amount_acct_ratio&quot;]  &gt; 1.8).mean()*100),<br>    (&quot;is_unusual_merchant&quot;,<br>     normal_df[&quot;is_unusual_merchant&quot;].mean()*100,<br>     fraud_df[&quot;is_unusual_merchant&quot;].mean()*100),<br>    (&quot;is_foreign&quot;,<br>     normal_df[&quot;is_foreign&quot;].mean()*100,<br>     fraud_df[&quot;is_foreign&quot;].mean()*100),<br>    (&quot;hour_deviation &gt; 3&quot;,<br>     (normal_df[&quot;hour_deviation&quot;] &gt; 3).mean()*100,<br>     (fraud_df[&quot;hour_deviation&quot;]  &gt; 3).mean()*100),<br>]<br>print(f&quot;  {&#39;Signal&#39;:&lt;26} {&#39;Normal&#39;:&gt;8} {&#39;Fraud&#39;:&gt;8} {&#39;Uplift&#39;:&gt;8}&quot;)<br>for name, n_val, f_val in dims:<br>    print(f&quot;  {name:&lt;26} {n_val:&gt;7.1f}% {f_val:&gt;7.1f}% {f_val/n_val:&gt;7.1f}×&quot;)<br><br>print(f&quot;\nState distribution:&quot;)<br>for s, name in {0:&#39;NORMAL&#39;,1:&#39;PROBING&#39;,2:&#39;FRAUD&#39;,3:&#39;DORMANT&#39;}.items():<br>    sub = df[df[&quot;_state&quot;]==s]<br>    if len(sub) == 0: continue<br>    print(f&quot;  {name:&lt;10}: {len(sub):&gt;8,} rows | &quot;<br>          f&quot;amt_mean={sub[&#39;txn_amount&#39;].mean():&gt;7.1f} | &quot;<br>          f&quot;unusual={sub[&#39;is_unusual_merchant&#39;].mean()*100:&gt;5.1f}% | &quot;<br>          f&quot;foreign={sub[&#39;is_foreign&#39;].mean()*100:&gt;4.1f}%&quot;)<br><br># Dataset : 500,000 | Frauds: 5,000 (1.00%)<br># Train   : 400,083 | Test: 99,917<br><br># Signal separation:<br>#   Signal                       Normal    Fraud   Uplift<br>#   amount_acct_ratio&gt;1.8         14.7%    45.2%     3.1×<br>#   is_unusual_merchant           40.1%    68.2%     1.7×<br>#   is_foreign                     8.1%    19.1%     2.4×<br>#   hour_deviation &gt; 3            49.9%    53.8%     1.1×<br><br># State distribution:<br>#   NORMAL    :  427,372 rows | amt_mean=  104.1 | unusual= 40.1% | foreign= 8.1%<br>#   PROBING   :   15,607 rows | amt_mean=   72.6 | unusual= 54.8% | foreign= 8.2%<br>#   FRAUD     :    5,000 rows | amt_mean=  195.1 | unusual= 68.2% | foreign=19.1%<br>#   DORMANT   :   52,021 rows | amt_mean=   27.3 | unusual= 20.1% | foreign= 3.0%</pre><p>Before writing a single line of model code, let’s understand what each architecture brings to fraud detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*trFIsh8Zin7pCE4gczUW2w.png" /></figure><h3>1. Logistic Regression — The Baseline</h3><p>Logistic Regression is not just a benchmark — it is still used in production at many financial institutions because it is fully explainable to regulators and auditors. Any model you propose needs to beat it significantly to justify the added complexity.</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from sklearn.pipeline import Pipeline<br>from sklearn.compose import ColumnTransformer<br>from sklearn.metrics import roc_auc_score, average_precision_score, brier_score_loss, log_loss<br><br>def evaluate(name, y_true, y_prob):<br>    auc   = roc_auc_score(y_true, y_prob)<br>    prauc = average_precision_score(y_true, y_prob)<br>    bs    = brier_score_loss(y_true, y_prob)<br>    bs_ref= brier_score_loss(y_true, np.full_like(y_prob, y_true.mean()))<br>    bss   = 1 - bs / bs_ref<br>    ll    = log_loss(y_true, y_prob)<br>    # ECE<br>    bins  = np.linspace(0, 1, 11)<br>    ece   = sum(<br>        mask.sum() * abs(y_prob[mask].mean() - y_true[mask].mean())<br>        for lo, hi in zip(bins[:-1], bins[1:])<br>        if (mask := (y_prob &gt;= lo) &amp; (y_prob &lt; hi)).sum() &gt; 0<br>    ) / len(y_true)<br><br>    print(f&quot;\n{&#39;─&#39;*45}&quot;)<br>    print(f&quot;  {name}&quot;)<br>    print(f&quot;{&#39;─&#39;*45}&quot;)<br>    print(f&quot;  AUC:       {auc:.4f}    PR-AUC: {prauc:.4f}&quot;)<br>    print(f&quot;  Brier:     {bs:.4f}    BSS:    {bss:.4f}&quot;)<br>    print(f&quot;  Log Loss:  {ll:.4f}    ECE:    {ece:.4f}&quot;)<br><br>X_tr = df_train[NUM_COLS + CAT_COLS]<br>y_tr = df_train[&quot;fraud&quot;].values<br>X_te = df_test[NUM_COLS + CAT_COLS]<br>y_te = df_test[&quot;fraud&quot;].values<br><br>prep = ColumnTransformer([<br>    (&quot;num&quot;, StandardScaler(), NUM_COLS),<br>    (&quot;cat&quot;, OneHotEncoder(handle_unknown=&quot;ignore&quot;, sparse_output=False), CAT_COLS),<br>])<br><br>base_lr = Pipeline([<br>    (&quot;prep&quot;, prep),<br>    (&quot;clf&quot;,  LogisticRegression(<br>        class_weight=&quot;balanced&quot;,<br>        C=1.0,              <br>        max_iter=1000, solver=&quot;lbfgs&quot;,<br>    ))<br>])<br><br># Hold out 15% of train for Platt calibration (same pattern as neural nets)<br># cv=5 is noisy at 1% fraud rate; held-out set is more stable<br>cal_cut = int(0.85 * len(X_tr))<br>X_fit, y_fit = X_tr.iloc[:cal_cut], y_tr[:cal_cut]<br>X_cal, y_cal = X_tr.iloc[cal_cut:], y_tr[cal_cut:]<br><br>base_lr.fit(X_fit, y_fit)<br><br>raw_cal = base_lr.predict_proba(X_cal)[:, 1]<br>raw_te  = base_lr.predict_proba(X_te)[:, 1]<br><br># Platt scaling: exact same approach as LSTM/TabTransformer/FT-Transformer<br>platt_lr = LogisticRegression(C=1e10, max_iter=1000)<br>platt_lr.fit(raw_cal.reshape(-1, 1), y_cal)<br>lr_proba = platt_lr.predict_proba(raw_te.reshape(-1, 1))[:, 1]<br><br>print(f&quot;Train: {len(X_fit):,}  Cal: {len(X_cal):,}  Test: {len(X_te):,}&quot;)<br>print(f&quot;Mean predicted: {lr_proba.mean():.5f}  &quot;<br>      f&quot;Ratio: {lr_proba.mean()/y_te.mean():.3f}x&quot;)<br>evaluate(&quot;Logistic Regression&quot;, y_te, lr_proba)<br><br># Train: 340,070  Cal: 60,013  Test: 99,917<br># Mean predicted: 0.01052  Ratio: 1.071x<br><br># ─────────────────────────────────────────────<br>#   Logistic Regression<br># ─────────────────────────────────────────────<br>#   AUC:       0.8196    PR-AUC: 0.0596<br>#   Brier:     0.0095    BSS:    0.0271<br>#   Log Loss:  0.0476    ECE:    0.0007</pre><blockquote>Why <em>class_weight=&quot;balanced&quot;</em> + Platt scaling, not isotonic?<br><em>class_weight=&quot;balanced&quot;</em> trains the model in a 50/50 world. The raw probabilities are inflated — they reflect a balanced dataset, not the real 1% fraud rate. Platt scaling corrects this with a two-parameter sigmoid fit. Isotonic regression has too many degrees of freedom at this imbalance ratio and produces.</blockquote><h3>2. XGBoost — The Incumbent Champion</h3><p>XGBoost handles mixed feature types natively, is robust to outliers (fraud transactions often have extreme values), and trains in seconds on 500,000 rows.</p><pre>from xgboost import XGBClassifier<br>from sklearn.calibration import CalibratedClassifierCV<br>from sklearn.frozen import FrozenEstimator<br>import pandas as pd<br><br># Encode cats as integer codes for XGBoost<br>def encode_cats(df_):<br>    d = df_[NUM_COLS + CAT_COLS].copy()<br>    for c in CAT_COLS:<br>        d[c] = d[c].cat.codes<br>    return d.values<br><br>X_tr_xgb = encode_cats(df_train);  y_tr_xgb = df_train[&quot;fraud&quot;].values<br>X_te_xgb = encode_cats(df_test);   y_te_xgb = df_test[&quot;fraud&quot;].values<br><br>scale_pos = (y_tr_xgb == 0).sum() / (y_tr_xgb == 1).sum()<br><br>xgb_base = XGBClassifier(<br>    n_estimators      = 500,<br>    max_depth         = 6,<br>    learning_rate     = 0.05,<br>    subsample         = 0.8,<br>    colsample_bytree  = 0.8,<br>    scale_pos_weight  = scale_pos,<br>    eval_metric       = &quot;aucpr&quot;,      <br>    early_stopping_rounds = 30,<br>    verbosity         = 0,<br>    random_state      = 42,<br>)<br>xgb_base.fit(<br>    X_tr_xgb, y_tr_xgb,<br>    eval_set=[(X_te_xgb, y_te_xgb)],<br>    verbose=False,<br>)<br><br>xgb_cal = CalibratedClassifierCV(<br>    FrozenEstimator(xgb_base), method=&quot;sigmoid&quot;, cv=5<br>)<br>xgb_cal.fit(X_tr_xgb, y_tr_xgb)<br><br>xgb_proba = xgb_cal.predict_proba(X_te_xgb)[:, 1]<br>print(f&quot;Best iteration: {xgb_base.best_iteration}&quot;)<br>print(f&quot;Mean predicted: {xgb_proba.mean():.5f}  &quot;<br>      f&quot;Ratio: {xgb_proba.mean()/y_te_xgb.mean():.3f}x&quot;)<br>evaluate(&quot;XGBoost&quot;, y_te_xgb, xgb_proba)<br><br># Best iteration: 152<br># Mean predicted: 0.00974  Ratio: 0.992x<br><br># ─────────────────────────────────────────────<br>#   XGBoost<br># ─────────────────────────────────────────────<br>#   AUC:       0.8295    PR-AUC: 0.0749<br>#   Brier:     0.0094    BSS:    0.0312<br>#   Log Loss:  0.0477    ECE:    0.0006</pre><h3>3. LSTM — The Sequential Specialist</h3><p>ATO fraud is inherently sequential — the probing phase precedes the fraud phase, and that temporal pattern is exactly what recurrent networks are built to detect. We use a GRU (Gated Recurrent Unit), a streamlined LSTM variant that trains faster with comparable performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*Dr26qYM0Uj-UQc8OyZHV0w.png" /></figure><pre>import os, random<br>os.environ[&quot;TF_DETERMINISTIC_OPS&quot;] = &quot;1&quot;<br><br>import numpy as np<br>import tensorflow as tf<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.layers import Input, GRU, Dense, Dropout, GaussianNoise<br>from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau<br>from sklearn.linear_model import LogisticRegression as PlattScaler<br>from sklearn.preprocessing import StandardScaler<br><br># ── Fix all random seeds ──────────────────────────────────────<br>random.seed(42)<br>np.random.seed(42)<br>tf.random.set_seed(42)<br><br>SEQ_LEN    = 10<br>LSTM_FEATS = NUM_COLS<br><br># ── Create df_seq — fit scaler on train only (no leakage) ─────<br>train_acct_set = set(df_train[&quot;account_id&quot;].unique())<br>df_seq = df.copy()<br>scaler_seq = StandardScaler()<br>train_mask = df[&quot;account_id&quot;].isin(train_acct_set)<br>scaler_seq.fit(df.loc[train_mask, NUM_COLS])           # fit on train only<br>df_seq[NUM_COLS] = scaler_seq.transform(df[NUM_COLS])  # transform all<br><br># ── Build sequences ───────────────────────────────────────────<br>seqs, labels, acct_ids = [], [], []<br>for acct, grp in df_seq.groupby(&quot;account_id&quot;, sort=False):<br>    arr = grp[LSTM_FEATS].values.astype(np.float32)<br>    y   = grp[&quot;fraud&quot;].values<br>    for i in range(SEQ_LEN, len(arr)+1):<br>        seqs.append(arr[i-SEQ_LEN:i])<br>        labels.append(y[i-1])<br>        acct_ids.append(acct)<br><br>X_seq    = np.array(seqs,   dtype=np.float32)<br>y_seq    = np.array(labels, dtype=np.float32)<br>acct_ids = np.array(acct_ids)<br><br># ── Account-based split ───────────────────────────────────────<br>tr_mask = np.array([a in train_acct_set for a in acct_ids])<br><br>X_tr_seq, y_tr_seq = X_seq[tr_mask],  y_seq[tr_mask]<br>X_te_seq, y_te_seq = X_seq[~tr_mask], y_seq[~tr_mask]<br><br># ── 85/15 fit/cal split ───────────────────────────────────────<br>cal_cut = int(0.85 * len(X_tr_seq))<br>X_fit, y_fit = X_tr_seq[:cal_cut], y_tr_seq[:cal_cut]<br>X_cal, y_cal = X_tr_seq[cal_cut:], y_tr_seq[cal_cut:]<br><br>pos_w = float((y_fit == 0).sum()) / float((y_fit == 1).sum())<br><br># ── Model ─────────────────────────────────────────────────────<br>n_feats = len(LSTM_FEATS)<br>inp = Input(shape=(SEQ_LEN, n_feats))<br>x   = GaussianNoise(0.05)(inp)<br>x   = GRU(32, return_sequences=False)(x)<br>x   = Dropout(0.4)(x)<br>x   = Dense(16, activation=&quot;relu&quot;)(x)<br>x   = Dropout(0.3)(x)<br>out = Dense(1, activation=&quot;sigmoid&quot;)(x)<br>model_gru = Model(inp, out)<br><br>model_gru.compile(<br>    optimizer=&quot;adam&quot;,<br>    loss=&quot;binary_crossentropy&quot;,<br>    metrics=[tf.keras.metrics.AUC(name=&quot;auc&quot;)],<br>)<br><br>early_stop = EarlyStopping(monitor=&quot;val_auc&quot;, patience=3,<br>                            restore_best_weights=True, mode=&quot;max&quot;)<br>reduce_lr  = ReduceLROnPlateau(monitor=&quot;val_auc&quot;, factor=0.5,<br>                                patience=2, mode=&quot;max&quot;, verbose=0)<br><br>model_gru.fit(<br>    X_fit, y_fit,<br>    sample_weight=np.where(y_fit==1, pos_w, 1.0),<br>    epochs=20, batch_size=512,<br>    validation_data=(X_cal, y_cal),<br>    callbacks=[early_stop, reduce_lr],<br>    verbose=0,<br>)<br><br># ── Platt scaling ─────────────────────────────────────────────<br>raw_cal = model_gru.predict(X_cal, verbose=0).ravel()<br>raw_te  = model_gru.predict(X_te_seq, verbose=0).ravel()<br><br>platt = PlattScaler(C=1e10, max_iter=1000)<br>platt.fit(raw_cal.reshape(-1,1), y_cal)<br>lstm_proba = platt.predict_proba(raw_te.reshape(-1,1))[:, 1]<br>lstm_y_te  = y_te_seq.copy()<br><br>print(f&quot;Mean predicted: {lstm_proba.mean():.5f}  &quot;<br>      f&quot;Ratio: {lstm_proba.mean()/lstm_y_te.mean():.3f}x&quot;)<br>evaluate(&quot;LSTM&quot;, lstm_y_te, lstm_proba)<br><br># Mean predicted: 0.01094  Ratio: 1.069x<br><br># ─────────────────────────────────────────────<br>#   LSTM<br># ─────────────────────────────────────────────<br>#   AUC:       0.8797    PR-AUC: 0.1730<br>#   Brier:     0.0095    BSS:    0.0633<br>#   Log Loss:  0.0444    ECE:    0.0018</pre><p>LSTM leads the leaderboard — not surprising. The ATO state machine creates a textbook sequential pattern: probing transactions are systematically smaller and home-merchant-concentrated, then the fraud transaction arrives with elevated amount and unusual merchant. A GRU with 10-step lookback sees this transition directly.</p><h3>4. TabTransformer — Attention on Categorical Features</h3><p>TabTransformer (Huang et al., 2020) was the first major paper to apply the Transformer architecture to tabular data. Its key insight: <strong>categorical features, when embedded and passed through multi-head attention layers, learn rich contextual representations</strong> that capture interactions between categories without manual feature engineering.</p><p>Numerical features are simply concatenated after layer normalisation — only the categoricals go through the attention mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*KW4cZer6IUdFP6DewhI3EQ.png" /></figure><pre>import torch<br>import torch.nn as nn<br>from torch.utils.data import DataLoader, TensorDataset<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LogisticRegression as PlattScaler<br>from sklearn.metrics import roc_auc_score<br><br># ── Encode ────────────────────────────────────────────────────<br>X_cat_all = np.stack([df[c].cat.codes.values for c in CAT_COLS], axis=1).astype(np.int64)<br>cat_dims  = [df[c].nunique() for c in CAT_COLS]<br><br>scaler_tt  = StandardScaler()<br>X_num_all  = scaler_tt.fit_transform(df[NUM_COLS].values).astype(np.float32)<br>y_all      = df[&quot;fraud&quot;].values.astype(np.float32)<br><br>tr_mask = df[&quot;account_id&quot;].isin(train_accts).values<br>te_mask = ~tr_mask<br><br>X_cat_tr, X_num_tr, y_tr_tt = X_cat_all[tr_mask], X_num_all[tr_mask], y_all[tr_mask]<br>X_cat_te, X_num_te, y_te_tt = X_cat_all[te_mask], X_num_all[te_mask], y_all[te_mask]<br><br># Reserve 15% of train for Platt calibration<br>cal_cut = int(0.85 * len(X_cat_tr))<br>X_cat_fit, X_num_fit, y_fit = X_cat_tr[:cal_cut], X_num_tr[:cal_cut], y_tr_tt[:cal_cut]<br>X_cat_cal, X_num_cal, y_cal = X_cat_tr[cal_cut:], X_num_tr[cal_cut:], y_tr_tt[cal_cut:]<br><br>def to_dl(xc, xn, yb, shuffle=False, bs=1024):<br>    ds = TensorDataset(torch.tensor(xc), torch.tensor(xn), torch.tensor(yb))<br>    return DataLoader(ds, batch_size=bs, shuffle=shuffle)<br><br>fit_dl = to_dl(X_cat_fit, X_num_fit, y_fit, shuffle=True)<br><br># ── Model ─────────────────────────────────────────────────────<br>class TabTransformer(nn.Module):<br>    def __init__(self, cat_dims, num_dim, d=32, n_heads=4, n_layers=3):<br>        super().__init__()<br>        self.embs = nn.ModuleList([nn.Embedding(d_+1, d) for d_ in cat_dims])<br>        enc = nn.TransformerEncoderLayer(<br>            d_model=d, nhead=n_heads, dim_feedforward=d*4,<br>            dropout=0.1, batch_first=True)<br>        self.transformer = nn.TransformerEncoder(<br>            enc, num_layers=n_layers, enable_nested_tensor=False)<br>        self.norm_num = nn.LayerNorm(num_dim)<br>        self.mlp = nn.Sequential(<br>            nn.Linear(len(cat_dims)*d + num_dim, 128), nn.ReLU(), nn.Dropout(0.2),<br>            nn.Linear(128, 64), nn.ReLU(), nn.Dropout(0.1),<br>            nn.Linear(64, 1),<br>        )<br>    def forward(self, xc, xn):<br>        e = torch.stack([emb(xc[:,i]) for i,emb in enumerate(self.embs)], dim=1)<br>        return self.mlp(torch.cat([self.transformer(e).flatten(1),<br>                                   self.norm_num(xn)], dim=1)).squeeze(1)<br><br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>tab_t  = TabTransformer(cat_dims, len(NUM_COLS)).to(device)<br>pos_w  = torch.tensor([(y_fit==0).sum()/(y_fit==1).sum()]).to(device)<br>crit   = nn.BCEWithLogitsLoss(pos_weight=pos_w)<br>opt    = torch.optim.AdamW(tab_t.parameters(), lr=1e-3, weight_decay=1e-4)<br>sched  = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=30)<br><br>best_auc, patience, best_state = 0, 5, None<br><br>for epoch in range(1, 31):<br>    tab_t.train()<br>    for xc, xn, yb in fit_dl:<br>        xc,xn,yb = xc.to(device), xn.to(device), yb.to(device)<br>        opt.zero_grad(); crit(tab_t(xc,xn), yb).backward(); opt.step()<br>    sched.step()<br>    tab_t.eval()<br>    with torch.no_grad():<br>        logits = tab_t(torch.tensor(X_cat_cal).to(device),<br>                       torch.tensor(X_num_cal).to(device)).cpu().numpy()<br>    auc = roc_auc_score(y_cal, logits)<br>    if auc &gt; best_auc:<br>        best_auc, patience, best_state = auc, 5, tab_t.state_dict().copy()<br>    else:<br>        patience -= 1<br>        if patience == 0:<br>            break<br><br>tab_t.load_state_dict(best_state)<br>tab_t.eval()<br><br># ── Platt scaling ─────────────────────────────────────────────<br>with torch.no_grad():<br>    raw_cal = tab_t(torch.tensor(X_cat_cal).to(device),<br>                    torch.tensor(X_num_cal).to(device)).cpu().numpy()<br>    raw_te  = tab_t(torch.tensor(X_cat_te).to(device),<br>                    torch.tensor(X_num_te).to(device)).cpu().numpy()<br><br>platt_tt = PlattScaler(C=1e10, max_iter=1000)<br>platt_tt.fit(raw_cal.reshape(-1,1), y_cal)<br>tabt_proba = platt_tt.predict_proba(raw_te.reshape(-1,1))[:, 1]<br><br>print(f&quot;Mean predicted: {tabt_proba.mean():.5f}  &quot;<br>      f&quot;Ratio: {tabt_proba.mean()/y_te_tt.mean():.3f}x&quot;)<br>evaluate(&quot;TabTransformer&quot;, y_te_tt, tabt_proba)<br><br># Mean predicted: 0.01042  Ratio: 1.062x<br><br># ─────────────────────────────────────────────<br>#   TabTransformer<br># ─────────────────────────────────────────────<br>#   AUC:       0.8257    PR-AUC: 0.0751<br>#   Brier:     0.0094    BSS:    0.0338<br>#   Log Loss:  0.0470    ECE:    0.0006</pre><h3>5. FT-Transformer — Attention on Everything</h3><p>Feature Tokenization Transformer (Gorishniy et al., 2021) takes the TabTransformer idea further: <strong>both numerical and categorical features are tokenized and passed through the Transformer</strong>. This allows attention to model interactions between any pair of features — a transaction amount interacting with the merchant category, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*3K3_tyEH0xV6A9BJJsUm_A.png" /></figure><pre>class FeatureTokenizer(nn.Module):<br>    def __init__(self, cat_dims, num_dim, d=32):<br>        super().__init__()<br>        self.cat_embs = nn.ModuleList([nn.Embedding(d_+1, d) for d_ in cat_dims])<br>        self.num_w    = nn.Parameter(torch.randn(num_dim, d) * 0.01)<br>        self.num_b    = nn.Parameter(torch.zeros(num_dim, d))<br>    def forward(self, xc, xn):<br>        cat_tok = [emb(xc[:,i]).unsqueeze(1) for i,emb in enumerate(self.cat_embs)]  # (B,1,d)<br>        num_tok = [(xn[:,i:i+1].unsqueeze(2) * self.num_w[i] + self.num_b[i])        # (B,1,d)<br>                   for i in range(xn.shape[1])]<br>        return torch.cat(cat_tok + num_tok, dim=1)   # (B, n_tokens, d)<br><br>class FTTransformer(nn.Module):<br>    def __init__(self, cat_dims, num_dim, d=32, n_heads=4, n_layers=3):<br>        super().__init__()<br>        self.tok  = FeatureTokenizer(cat_dims, num_dim, d)<br>        self.cls  = nn.Parameter(torch.zeros(1, 1, d))<br>        enc = nn.TransformerEncoderLayer(<br>            d_model=d, nhead=n_heads, dim_feedforward=d*4,<br>            dropout=0.1, batch_first=True)<br>        self.transformer = nn.TransformerEncoder(<br>            enc, num_layers=n_layers, enable_nested_tensor=False)<br>        self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 1))<br>    def forward(self, xc, xn):<br>        tok = self.tok(xc, xn)<br>        cls = self.cls.expand(tok.size(0), -1, -1)<br>        x   = self.transformer(torch.cat([cls, tok], dim=1))<br>        return self.head(x[:, 0]).squeeze(1)   # [CLS] token → output<br><br># Reuse same train/cal/test splits from TabTransformer cell<br>ft_t  = FTTransformer(cat_dims, len(NUM_COLS)).to(device)<br>opt_ft = torch.optim.AdamW(ft_t.parameters(), lr=1e-3, weight_decay=1e-4)<br>sched_ft = torch.optim.lr_scheduler.CosineAnnealingLR(opt_ft, T_max=30)<br>pos_w_ft = torch.tensor([(y_fit==0).sum()/(y_fit==1).sum()]).to(device)<br>crit_ft  = nn.BCEWithLogitsLoss(pos_weight=pos_w_ft)<br><br>best_auc, patience, best_state = 0, 5, None<br><br>for epoch in range(1, 31):<br>    ft_t.train()<br>    for xc, xn, yb in fit_dl:<br>        xc,xn,yb = xc.to(device), xn.to(device), yb.to(device)<br>        opt_ft.zero_grad(); crit_ft(ft_t(xc,xn), yb).backward(); opt_ft.step()<br>    sched_ft.step()<br>    ft_t.eval()<br>    with torch.no_grad():<br>        logits = ft_t(torch.tensor(X_cat_cal).to(device),<br>                      torch.tensor(X_num_cal).to(device)).cpu().numpy()<br>    auc = roc_auc_score(y_cal, logits)<br>  <br>    if auc &gt; best_auc:<br>        best_auc, patience, best_state = auc, 5, ft_t.state_dict().copy()<br>    else:<br>        patience -= 1<br>        if patience == 0:<br>            break<br><br>ft_t.load_state_dict(best_state)<br>ft_t.eval()<br><br># ── Platt scaling ─────────────────────────────────────────────<br>with torch.no_grad():<br>    raw_cal_ft = ft_t(torch.tensor(X_cat_cal).to(device),<br>                      torch.tensor(X_num_cal).to(device)).cpu().numpy()<br>    raw_te_ft  = ft_t(torch.tensor(X_cat_te).to(device),<br>                      torch.tensor(X_num_te).to(device)).cpu().numpy()<br><br>platt_ft = PlattScaler(C=1e10, max_iter=1000)<br>platt_ft.fit(raw_cal_ft.reshape(-1,1), y_cal)<br>ft_proba = platt_ft.predict_proba(raw_te_ft.reshape(-1,1))[:, 1]<br><br>print(f&quot;Mean predicted: {ft_proba.mean():.5f}  &quot;<br>      f&quot;Ratio: {ft_proba.mean()/y_te_tt.mean():.3f}x&quot;)<br>evaluate(&quot;FT-Transformer&quot;, y_te_tt, ft_proba)<br><br># Mean predicted: 0.01059  Ratio: 1.079x<br><br># ─────────────────────────────────────────────<br>#   FT-Transformer<br># ─────────────────────────────────────────────<br>#   AUC:       0.8286    PR-AUC: 0.0680<br>#   Brier:     0.0094    BSS:    0.0302<br>#   Log Loss:  0.0471    ECE:    0.0009</pre><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*0H2AYDHPHBUBTakRmQ4jJQ.png" /></figure><p>The Transformer vs. XGBoost debate in fraud detection resolves differently depending on fraud type and data structure.</p><p>On <strong>account takeover fraud</strong> with sequential transaction data, a well-calibrated GRU sees the probing-then-fraud pattern directly and leads the leaderboard. This is the sequential specialist advantage — not a general result.</p><p>On <strong>flat tabular classification</strong> (single-transaction features, no sequence), XGBoost and FT-Transformer reach statistical parity at ~0.83 AUC on 500,000 rows. The 0.003 gap between them is within run-to-run noise. FT-Transformer achieves this without any feature engineering, interaction design, or sequence construction — notable for a model that did not exist five years ago.</p><p>TabTransformer’s gap behind FT-Transformer is instructive: limiting attention to categorical features only misses the joint signal between numerical and categorical dimensions. If you are going to use a Transformer on tabular fraud data, use FT-Transformer.</p><p><strong>Practical recommendation for 2026 fraud teams:</strong> Start with XGBoost as your tabular baseline. If you have account-level transaction sequences, benchmark GRU. If you are on a large dataset (&gt; 100,000 rows) and want to explore attention without sequence engineering, FT-Transformer is the right Transformer to reach for. In all cases, validate calibration with ratio checks before production deployment.</p><blockquote>The best model is not the most complex one. It is the one whose predictions you can stand behind in front of a risk committee — and whose probabilities an expected-loss model can actually use.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cbf96b0836d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measuring What Matters: A Complete Guide to Model Evaluation Metrics in Credit Risk]]></title>
            <link>https://medium.com/@yfwei0225/measuring-what-matters-a-complete-guide-to-model-evaluation-metrics-in-credit-risk-3fdca30f62cc?source=rss-33009d208c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fdca30f62cc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[credit-risk-modelling]]></category>
            <dc:creator><![CDATA[Emma Wei]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 01:48:39 GMT</pubDate>
            <atom:updated>2026-06-16T02:31:55.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Anstx5bzkX98UZPVGXTV5A.png" /></figure><blockquote>AUC/Gini measure how well your model ranks risk. KS shows where that separation peaks. PR-AUC is the honest metric when defaults are rare. Brier Score and Log-Loss check whether your probabilities are actually correct. Information Value picks your features. All of them together tell the full story.</blockquote><h3>1. Introduction</h3><p>Credit risk modeling sits at the intersection of statistics, finance, and regulation. A model that predicts which borrowers will default can save a bank millions in charge-offs, enable fairer lending decisions, and satisfy the scrutiny of regulators under CECL, Basel IV, and IFRS 9. But a model is only as good as our ability to measure it — and measuring it well is far less straightforward than it first appears.</p><p>This guide is a practitioner-level deep dive into every meaningful metric used to evaluate binary classification models in credit risk. We cover discriminatory power (AUC, Gini, KS), calibration (Brier Score, Log-Loss), precision-recall performance (PR-AUC), and feature-level analysis (WoE, IV). For each metric we explain the intuition, the math, industry benchmarks, and provide production-ready Python code.</p><blockquote>A model with a great AUC but poor calibration may rank borrowers correctly but produce reserve estimates that are completely wrong. You need both.</blockquote><h4>Setting Up: Our Test Dataset</h4><p>Throughout this guide we use a single synthetic credit dataset — 10,000 loans with a 5% default rate.</p><pre>import numpy as np, pandas as pd, matplotlib.pyplot as plt<br>from sklearn.metrics import (roc_auc_score, roc_curve,<br>    precision_recall_curve, average_precision_score,<br>    brier_score_loss, log_loss)<br>from sklearn.calibration import calibration_curve<br><br>np.random.seed(42)<br>n = 10_000<br><br>y_true  = np.random.binomial(1, 0.05, n)<br>signal  = np.where(y_true == 1, 0.6, 0.3)<br>noise   = np.random.normal(0, 0.25, n)<br>y_score = np.clip(signal + noise, 0, 1)<br><br>print(f&quot;Dataset: {n:,} loans | {y_true.sum():,} defaults ({y_true.mean():.0%} rate)&quot;)<br><br># Dataset: 10,000 loans | 474 defaults (5% rate)</pre><h4>The Class Imbalance Problem</h4><p>Before any metric makes sense, appreciate the core challenge: default events are rare. A 5% default rate means 95 out of every 100 rows are non-defaults.</p><blockquote>⚠️ <strong>Warning:</strong> A model that predicts “no default” for every single borrower achieves <strong>95% accuracy</strong> on a 5% default-rate portfolio — and is completely useless. Accuracy is not a valid metric for credit risk. Never use it as your primary evaluation criterion.</blockquote><p>Key implications:</p><ul><li>The False Positive Rate denominator is dominated by the huge non-default class, making ROC-AUC appear better than reality</li><li>PR-AUC and KS are anchored to the positive (default) class, making them more honest on imbalanced data</li><li>Calibration metrics are critical when probabilities drive reserve calculations, not just ranking</li></ul><h3>2. AUC — Area Under the ROC Curve</h3><p>The ROC curve plots True Positive Rate (Sensitivity) on the y-axis against False Positive Rate on the x-axis at every possible threshold. AUC — the area under that curve — has one of the most intuitive probabilistic interpretations in machine learning:</p><p><strong>AUC = P( score(default) &gt; score(non-default) )</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*GVq8yCnFbEtLNWWzjSUoUg.png" /></figure><pre>from sklearn.metrics import roc_auc_score, roc_curve<br><br>auc = roc_auc_score(y_true, y_score)<br>fpr, tpr, _ = roc_curve(y_true, y_score)<br><br>print(f&quot;AUC: {auc:.4f}&quot;)<br><br>plt.figure(figsize=(7, 5))<br>plt.plot(fpr, tpr, color=&quot;steelblue&quot;, lw=2, label=f&quot;ROC Curve (AUC = {auc:.4f})&quot;)<br>plt.plot([0,1], [0,1], &quot;k--&quot;, lw=1, label=&quot;Random (AUC = 0.50)&quot;)<br>plt.fill_between(fpr, tpr, alpha=0.10, color=&quot;steelblue&quot;)<br>plt.xlabel(&quot;False Positive Rate&quot;); plt.ylabel(&quot;True Positive Rate&quot;)<br>plt.title(&quot;ROC Curve&quot;); plt.legend(loc= (0.5, 0.3), frameon = False)<br>plt.tight_layout();  plt.show()<br><br># AUC: 0.8106</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Q8GcDE3EOAjjvqPIVpn2jw.png" /></figure><p>An AUC of 0.81 means: if you randomly pick one defaulter and one non-defaulter, there is an 81% chance the model assigns a higher risk score to the defaulter.</p><h3>3. Gini Coefficient</h3><p>Gini is AUC in different clothes — a linear rescaling so that 0 means random and 1 means perfect:</p><p><strong>Gini = 2 × AUC − 1</strong></p><p>It originates from income inequality economics but was adopted by credit risk because of its elegant graphical interpretation via the <strong>Lorenz Curve</strong>. Rank your portfolio by predicted risk (riskiest first), plot cumulative population share vs. cumulative defaults captured — the Gini is twice the area between this curve and the 45-degree diagonal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*0K1mU0J-ITtgCyEx58dXBw.png" /></figure><pre>auc  = roc_auc_score(y_true, y_score)<br>gini = 2 * auc - 1<br>print(f&quot;AUC : {auc:.4f}&quot;)<br>print(f&quot;Gini: {gini:.4f}&quot;)<br><br># Lorenz curve<br>df = pd.DataFrame({&quot;y&quot;: y_true, &quot;score&quot;: y_score})<br>df = df.sort_values(&quot;score&quot;, ascending=False).reset_index(drop=True)<br>df[&quot;cum_pop&quot;]    = (df.index + 1) / len(df)<br>df[&quot;cum_events&quot;] = df[&quot;y&quot;].cumsum() / df[&quot;y&quot;].sum()<br><br>plt.figure(figsize=(7, 5))<br>plt.plot(df[&quot;cum_pop&quot;], df[&quot;cum_events&quot;],<br>         color=&quot;steelblue&quot;, lw=2, label=f&quot;Model (Gini = {gini:.4f})&quot;)<br>plt.fill_between(df[&quot;cum_pop&quot;], df[&quot;cum_events&quot;], df[&quot;cum_pop&quot;],<br>                 alpha=0.15, color=&quot;steelblue&quot;, label=&quot;Gini area&quot;)<br>plt.plot([0,1],[0,1], &quot;k--&quot;, lw=1, label=&quot;Random&quot;)<br>plt.plot([0,0,1],[0,1,1], &quot;g--&quot;, lw=1, label=&quot;Perfect&quot;)<br>plt.xlabel(&quot;Cumulative % Population&quot;); plt.ylabel(&quot;Cumulative % Defaults&quot;)<br>plt.title(&quot;Lorenz Curve&quot;); plt.legend(frameon = False); plt.tight_layout()<br>plt.show()<br><br># AUC : 0.8106<br># Gini: 0.6212</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*xo9Ay2QGVU2nthbC47I9Yw.png" /></figure><blockquote>Gini is the credit risk practitioner’s favorite metric. It appears in every model validation report, every regulatory submission, and every risk committee deck. Master it first.</blockquote><h3>4. KS Statistic — Kolmogorov-Smirnov</h3><p>KS measures the <strong>maximum vertical separation</strong> between the CDFs of the defaulter and non-defaulter score distributions. Unlike AUC, which summarises performance across all thresholds, KS points to one specific cutoff — the score where the model best separates the two classes.</p><p>KS = max | CDF(defaults) − CDF(non-defaults) | × 100</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*mG5WXPZ9oKlGl_AUBlByPQ.png" /></figure><pre>def compute_ks(y_true, y_score, n_bins=10):<br>    df = pd.DataFrame({&quot;y&quot;: y_true, &quot;score&quot;: y_score})<br>    df[&quot;decile&quot;] = pd.qcut(df[&quot;score&quot;], q=n_bins,<br>                           labels=False, duplicates=&quot;drop&quot;)<br>    df[&quot;decile&quot;] = n_bins - df[&quot;decile&quot;]  # flip: high score = high risk<br>    tbl = df.groupby(&quot;decile&quot;).agg(n=(&quot;y&quot;,&quot;count&quot;), bads=(&quot;y&quot;,&quot;sum&quot;)).reset_index()<br>    tbl[&quot;goods&quot;]     = tbl[&quot;n&quot;] - tbl[&quot;bads&quot;]<br>    tbl[&quot;cum_bads&quot;]  = tbl[&quot;bads&quot;].cumsum()  / tbl[&quot;bads&quot;].sum()<br>    tbl[&quot;cum_goods&quot;] = tbl[&quot;goods&quot;].cumsum() / tbl[&quot;goods&quot;].sum()<br>    tbl[&quot;KS&quot;]        = (tbl[&quot;cum_bads&quot;] - tbl[&quot;cum_goods&quot;]).abs() * 100<br>    return tbl<br><br>ks_tbl = compute_ks(y_true, y_score)<br>ks_val = ks_tbl[&quot;KS&quot;].max()<br>print(ks_tbl[[&quot;decile&quot;,&quot;n&quot;,&quot;bads&quot;,&quot;goods&quot;,&quot;cum_bads&quot;,&quot;cum_goods&quot;,&quot;KS&quot;]])<br>print(f&quot;\nKS Statistic: {ks_val:.2f}&quot;)<br><br>#    decile     n  bads  goods  cum_bads  cum_goods         KS<br># 0       2  1000   210    790  0.443038   0.082931  36.010705<br># 1       3  1000    90    910  0.632911   0.178459  45.445244<br># 2       4  1000    53    947  0.744726   0.277871  46.685465<br># 3       5  1000    39    961  0.827004   0.378753  44.825133<br># 4       6  1000    26    974  0.881857   0.480999  40.085717<br># 5       7  1000    18    982  0.919831   0.584086  33.574556<br># 6       8  1000    22    978  0.966245   0.686752  27.949268<br># 7       9  1000     8    992  0.983122   0.790888  19.223427<br># 8      10  2000     8   1992  1.000000   1.000000   0.000000<br><br># KS Statistic: 46.69</pre><h3>5. PR-AUC — Precision-Recall Area Under the Curve</h3><blockquote>💡 KS and AUC tell different stories. A high KS with a modest AUC means the model has a strong sweet spot but poor ranking overall. Always report both.</blockquote><p>Here is the uncomfortable truth about ROC-AUC: it can look impressive even when your model is mediocre at identifying actual defaults. The False Positive Rate denominator is dominated by the 95,000 non-defaults in your dataset — the ROC curve is <strong>flattered by the abundance of true negatives</strong>.</p><p>Precision-Recall sidesteps this problem by ignoring true negatives entirely:</p><ul><li><strong>Precision</strong> = TP / (TP + FP) — of those flagged as defaults, how many actually defaulted?</li><li><strong>Recall</strong> = TP / (TP + FN) — of all actual defaults, how many did we catch?</li></ul><blockquote>PR-AUC ignores true negatives completely. It only asks: of the defaults that exist, how many did you find, and how precise were you? That is a much harder and more honest question.</blockquote><p><strong>PR-AUC baseline = P(Y = 1) = event rate (NOT 0.50)</strong></p><p>A random classifier on a 5% default rate achieves PR-AUC ≈ <strong>0.05</strong>, not 0.50. A model with PR-AUC = 0.25 represents a <strong>5× lift</strong> over random.</p><pre>from sklearn.metrics import precision_recall_curve, average_precision_score<br><br>precision, recall, _ = precision_recall_curve(y_true, y_score)<br>pr_auc   = average_precision_score(y_true, y_score)<br>baseline = y_true.mean()<br><br>print(f&quot;PR-AUC   : {pr_auc:.4f}&quot;)<br>print(f&quot;Baseline : {baseline:.2f}  (random classifier)&quot;)<br>print(f&quot;Lift     : {pr_auc / baseline:.2f}x over random&quot;)<br><br>plt.figure(figsize=(7, 5))<br>plt.plot(recall, precision, color=&quot;darkorange&quot;, lw=2,<br>         label=f&quot;PR Curve (AP = {pr_auc:.4f})&quot;)<br>plt.axhline(baseline, color=&quot;gray&quot;, ls=&quot;--&quot;,<br>            label=f&quot;Random baseline ({baseline:.2f})&quot;)<br>plt.fill_between(recall, precision, alpha=0.10, color=&quot;darkorange&quot;)<br>plt.xlabel(&quot;Recall&quot;); plt.ylabel(&quot;Precision&quot;)<br>plt.title(&quot;Precision-Recall Curve&quot;)<br>plt.legend(frameon = False); plt.tight_layout()<br>plt.show()<br><br># PR-AUC   : 0.2268<br># Baseline : 0.05  (random classifier)<br># Lift     : 4.79x over random</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*QxdzGn0i5jCbX4nPO0ZjIQ.png" /></figure><h3>6. Brier Score and Brier Skill Score</h3><p>All the metrics above measure <strong>discrimination</strong> — can the model rank borrowers correctly? The Brier Score measures something different: <strong>calibration</strong>.</p><blockquote><em>🎯 Calibration question: when the model says “5% probability of default,” do approximately 5% of those borrowers actually default? Discrimination metrics cannot answer this. Brier Score can.</em></blockquote><p><strong>Brier Score = (1/n) × Σ (ŷᵢ − yᵢ)²</strong></p><p>A perfect model achieves BS = 0. The <strong>Brier Skill Score</strong> normalises against the null model (predicting the mean for everyone):</p><p><strong>BSS = 1 − BS / BS_null (1 = perfect, 0 = no skill)</strong></p><pre>from sklearn.metrics import brier_score_loss<br><br>brier   = brier_score_loss(y_true, y_score)<br>null_bs = y_true.mean() * (1 - y_true.mean())<br>bss     = 1 - brier / null_bs<br><br>print(f&quot;Brier Score      : {brier:.4f}  (lower is better; 0 = perfect)&quot;)<br>print(f&quot;Null Brier Score : {null_bs:.4f}&quot;)<br>print(f&quot;Brier Skill Score: {bss:.4f}  (higher is better; 1 = perfect)&quot;)<br><br># Brier Score      : 0.1161  (lower is better; 0 = perfect)<br># Null Brier Score : 0.0452<br># Brier Skill Score: -1.5716  (higher is better; 1 = perfect)</pre><h3>7. Log-Loss and the Calibration Curve</h3><p>Log-Loss (binary cross-entropy) differs from Brier Score in one important way: the logarithm <strong>severely penalises confident wrong predictions</strong>. Saying “99% chance of no default” when the borrower defaults incurs an astronomically larger penalty than saying “55% chance.”</p><p><strong>Log-Loss = −(1/n) × Σ [ yᵢ log(pᵢ) + (1−yᵢ) log(1−pᵢ) ]</strong></p><p><strong>Calibration Curve (Reliability Diagram)</strong>: The most direct visual test of calibration — plot mean predicted probability vs. actual observed rate per bin. A perfectly calibrated model follows the 45-degree diagonal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*MTDlNT4CvagTeGAeIkxStg.png" /></figure><p><strong>Fixing Miscalibration: Platt Scaling and Isotonic Regression</strong></p><p>Calibration techniques are post-processing steps applied after the model is trained. They remap raw scores to well-calibrated probabilities without touching the underlying model’s discriminatory power (AUC and KS remain unchanged).</p><p>Platt Scaling fits a logistic regression — just a sigmoid with two learned parameters — on top of the raw scores. It assumes the miscalibration follows a sigmoid shape, making it ideal for the common S-curve pattern. It is robust even with limited data.</p><p>Isotonic Regression fits a monotonic step function with no shape constraints. It is more flexible and can correct arbitrary calibration errors, but requires more data and can overfit on small samples.</p><blockquote>In practice: use Platt scaling for IFRS 9 or CECL PD models where you want a theoretically grounded, auditable calibration adjustment. Use isotonic regression when you have large out-of-time samples and want maximum flexibility.</blockquote><pre>from sklearn.metrics import log_loss, brier_score_loss<br>from sklearn.calibration import calibration_curve<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.isotonic import IsotonicRegression<br><br># ── Fit on full dataset ────────────────────────────────────────<br>platt = LogisticRegression()<br>platt.fit(y_score.reshape(-1, 1), y_true)<br>y_platt = platt.predict_proba(y_score.reshape(-1, 1))[:, 1]<br><br>iso = IsotonicRegression(out_of_bounds=&quot;clip&quot;)<br>iso.fit(y_score, y_true)<br>y_iso = iso.predict(y_score)<br><br># ── Compare ────────────────────────────────────────────────────<br>null_bs = y_true.mean() * (1 - y_true.mean())<br><br>def eval_cal(name, y_pred):<br>    bs  = brier_score_loss(y_true, y_pred)<br>    bss = 1 - bs / null_bs<br>    ll  = log_loss(y_true, y_pred)<br>    print(f&quot;{name:25s} | BSS: {bss:+.4f} | Log-Loss: {ll:.4f} | Mean PD: {y_pred.mean():.4f}&quot;)<br><br>print(f&quot;Actual default rate: {y_true.mean():.4f}&quot;)<br>print(&quot;-&quot; * 72)<br>eval_cal(&quot;Uncalibrated&quot;,        y_score)<br>eval_cal(&quot;Platt Scaling&quot;,       y_platt)<br>eval_cal(&quot;Isotonic Regression&quot;, y_iso)<br><br># Actual default rate: 0.0474<br># ------------------------------------------------------------------------<br># Uncalibrated              | BSS: -2.3988 | Log-Loss: 0.5472 | Mean PD: 0.3302<br># Platt Scaling             | BSS: +0.1006 | Log-Loss: 0.1579 | Mean PD: 0.0474<br># Isotonic Regression       | BSS: +0.1075 | Log-Loss: 0.1560 | Mean PD: 0.0474</pre><p>The mean predicted PD drops from 33% to 4.7% — matching the actual default rate — and BSS flips from deeply negative to positive. Critically, AUC and KS are unaffected because both calibration methods are monotonic transformations of the original scores.</p><pre>fig, ax = plt.subplots(figsize=(7, 5))<br><br>for name, y_pred, color in [<br>    (&quot;Uncalibrated&quot;,        y_score, &quot;red&quot;),<br>    (&quot;Platt Scaling&quot;,       y_platt, &quot;steelblue&quot;),<br>    (&quot;Isotonic Regression&quot;, y_iso,   &quot;green&quot;),<br>]:<br>    frac_pos, mean_pred = calibration_curve(<br>        y_true, y_pred, n_bins=10, strategy=&quot;quantile&quot;<br>    )<br>    ax.plot(mean_pred, frac_pos, &quot;s-&quot;, color=color, lw=2, label=name)<br><br>ax.plot([0, 1], [0, 1], &quot;k--&quot;, lw=1, label=&quot;Perfect calibration&quot;)<br>ax.set_xlabel(&quot;Mean Predicted Probability&quot;)<br>ax.set_ylabel(&quot;Fraction of Positives (Actual Default Rate)&quot;)<br>ax.set_title(&quot;Calibration Curves — Before vs. After Recalibration&quot;)<br>ax.legend()<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*rBYH6GoaQjIWD1nbgkCfXg.png" /></figure><h3>8. Weight of Evidence and Information Value</h3><p>WoE and IV operate at the <strong>variable level</strong>, not the model level. Before you train anything, IV tells you which features are worth including and how to bin them.</p><p><strong>WoE_i = ln( Events%_i / Non-Events%_i )</strong></p><p><strong>IV = Σ ( Events%_i − Non-Events%_i ) × WoE_i</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*7IYN0xvkCeZq236fjb8WIQ.png" /></figure><pre>def information_value(y_true, score, n_bins=10):<br>    df = pd.DataFrame({&quot;y&quot;: y_true, &quot;score&quot;: score})<br>    df[&quot;bin&quot;] = pd.qcut(df[&quot;score&quot;], q=n_bins, labels=False, duplicates=&quot;drop&quot;)<br>    total_bads  = df[&quot;y&quot;].sum()<br>    total_goods = len(df) - total_bads<br>    rows = []<br>    for b, grp in df.groupby(&quot;bin&quot;):<br>        bads  = grp[&quot;y&quot;].sum()<br>        goods = len(grp) - bads<br>        pct_b = bads  / total_bads  if total_bads  else 0<br>        pct_g = goods / total_goods if total_goods else 0<br>        woe   = np.log(pct_b / pct_g) if pct_b &gt; 0 and pct_g &gt; 0 else 0<br>        rows.append({&quot;bin&quot;: b, &quot;bads&quot;: bads, &quot;goods&quot;: goods,<br>                     &quot;pct_bads&quot;: pct_b, &quot;pct_goods&quot;: pct_g,<br>                     &quot;WoE&quot;: round(woe, 4), &quot;IV&quot;: round((pct_b-pct_g)*woe, 4)})<br>    tbl = pd.DataFrame(rows)<br>    print(tbl.to_string(index=False))<br>    print(f&quot;\nTotal IV: {tbl[&#39;IV&#39;].sum():.4f}&quot;)<br>    return tbl<br><br># Add noise to reduce separation to realistic levels<br>noise   = np.random.normal(0, 0.5, n)<br>y_score2 = np.clip(y_score + noise, 0, 1)<br><br>iv_tbl = information_value(y_true, y_score2)<br><br>#  bin  bads  goods  pct_bads  pct_goods     WoE     IV<br>#    0    71   2929  0.149789   0.307474 -0.7192 0.1134<br>#    1    34    966  0.071730   0.101407 -0.3462 0.0103<br>#    2    39    961  0.082278   0.100882 -0.2038 0.0038<br>#    3    47    953  0.099156   0.100042 -0.0089 0.0000<br>#    4    58    942  0.122363   0.098887  0.2130 0.0050<br>#    5    57    943  0.120253   0.098992  0.1946 0.0041<br>#    6   168   1832  0.354430   0.192316  0.6114 0.0991<br><br># Total IV: 0.2357</pre><h3>9. Capture Rate and Gains Analysis</h3><p>All the metrics above are about quality. Capture rate is about <strong>value</strong>.</p><blockquote>If reviewing the top 20% of the portfolio — the highest-risk quintile — contains 63% of all defaults at 3.2× lift. The bottom 60% of the book holds only 8% of the credit risk.— and that numbers go directly into business case ROI calculations.</blockquote><pre>def gains_table(y_true, y_score, n_deciles=5, label=&quot;&quot;):<br>    df = pd.DataFrame({&quot;y&quot;: y_true, &quot;score&quot;: y_score})<br>    df = df.sort_values(&quot;score&quot;, ascending=False).reset_index(drop=True)<br>    total_bads = df[&quot;y&quot;].sum()<br>    df[&quot;decile&quot;] = np.clip(df.index // (len(df) // n_deciles) + 1, 1, n_deciles)  # ← fix<br>    tbl = df.groupby(&quot;decile&quot;).agg(n=(&quot;y&quot;,&quot;count&quot;), bads=(&quot;y&quot;,&quot;sum&quot;)).reset_index()<br>    tbl[&quot;cum_n&quot;]        = tbl[&quot;n&quot;].cumsum()<br>    tbl[&quot;cum_bads&quot;]     = tbl[&quot;bads&quot;].cumsum()<br>    tbl[&quot;pct_pop&quot;]      = tbl[&quot;cum_n&quot;]    / len(df)    * 100<br>    tbl[&quot;capture_rate&quot;] = tbl[&quot;cum_bads&quot;] / total_bads * 100<br>    tbl[&quot;lift&quot;]         = tbl[&quot;capture_rate&quot;] / tbl[&quot;pct_pop&quot;]<br>    print(tbl[[&quot;decile&quot;,&quot;n&quot;,&quot;bads&quot;,&quot;pct_pop&quot;,&quot;capture_rate&quot;,&quot;lift&quot;]].to_string(index=False))<br>    return tbl<br><br>gt_platt = gains_table(y_true, y_platt, n_deciles=5, label=&quot;Platt Scaled&quot;)<br><br>fig, ax = plt.subplots(figsize=(8, 5))<br>ax.plot(gt_platt[&quot;pct_pop&quot;], gt_platt[&quot;capture_rate&quot;], &quot;o-&quot;, color=&quot;steelblue&quot;, lw=2, label=&quot;Platt Scaled&quot;)<br>ax.plot([0, 100], [0, 100], &quot;k--&quot;, lw=1, label=&quot;Random&quot;)<br>ax.set_xlabel(&quot;% Population Reviewed&quot;)<br>ax.set_ylabel(&quot;% Defaults Captured&quot;)<br>ax.set_title(&quot;Gains Chart — Platt Scaled&quot;)<br>ax.legend()<br>ax.grid(True, alpha=0.3)<br>plt.tight_layout()<br>plt.show()<br><br>  # decile    n  bads  pct_pop  capture_rate     lift<br>  #     1 2000   300     20.0     63.291139 3.164557<br>  #     2 2000    92     40.0     82.700422 2.067511<br>  #     3 2000    44     60.0     91.983122 1.533052<br>  #     4 2000    30     80.0     98.312236 1.228903<br>  #     5 2000     8    100.0    100.000000 1.000000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*EHJbznKNU7VODuphZ1xtng.png" /></figure><h3>10. The Complete Model Scorecard</h3><pre>def model_scorecard(y_true, y_score, model_name=&quot;Model v1.0&quot;):<br>    auc    = roc_auc_score(y_true, y_score)<br>    gini   = 2 * auc - 1<br>    ks     = compute_ks(y_true, y_score)[&quot;KS&quot;].max()<br>    pr_auc = average_precision_score(y_true, y_score)<br>    rate   = y_true.mean()<br>    brier  = brier_score_loss(y_true, y_score)<br>    bss    = 1 - brier / (rate * (1 - rate))<br>    ll     = log_loss(y_true, y_score)<br><br>    sep = &quot;=&quot; * 50<br>    print(sep)<br>    print(f&quot;  MODEL SCORECARD: {model_name}&quot;)<br>    print(sep)<br>    print(f&quot;  DISCRIMINATORY POWER&quot;)<br>    print(f&quot;    AUC              : {auc:.4f}&quot;)<br>    print(f&quot;    Gini             : {gini:.4f}&quot;)<br>    print(f&quot;    KS               : {ks:.2f}&quot;)<br>    print(f&quot;  PRECISION-RECALL&quot;)<br>    print(f&quot;    PR-AUC           : {pr_auc:.4f}&quot;)<br>    print(f&quot;    Lift over random : {pr_auc/rate:.2f}x&quot;)<br>    print(f&quot;  CALIBRATION (Platt Scaled)&quot;)<br>    print(f&quot;    Brier Score      : {brier:.4f}&quot;)<br>    print(f&quot;    Brier Skill Score: {bss:.4f}&quot;)<br>    print(f&quot;    Log-Loss         : {ll:.4f}&quot;)<br>    print(f&quot;    Mean PD          : {y_score.mean():.4f}&quot;)<br>    print(f&quot;    Actual default   : {rate:.4f}&quot;)<br>    print(sep)<br><br>model_scorecard(y_true, y_platt, &quot;Credit PD v1.0 — Platt Scaled&quot;)<br><br># ==================================================<br>#   MODEL SCORECARD: Credit PD v1.0 — Platt Scaled<br># ==================================================<br>#   DISCRIMINATORY POWER<br>#     AUC              : 0.8106<br>#     Gini             : 0.6212<br>#     KS               : 46.69<br>#   PRECISION-RECALL<br>#     PR-AUC           : 0.2268<br>#     Lift over random : 4.79x<br>#   CALIBRATION (Platt Scaled)<br>#     Brier Score      : 0.0406<br>#     Brier Skill Score: 0.1006<br>#     Log-Loss         : 0.1579<br>#     Mean PD          : 0.0474<br>#     Actual default   : 0.0474<br># ==================================================</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*1e_Zqg6-HdNtNL53KJH8jw.png" /></figure><h3>11. Five Pitfalls That Fool Even Experienced Modellers</h3><p><strong>(1) Confusing Discrimination with Calibration</strong></p><p>A model can rank borrowers in perfect order (AUC = 1.0) while predicting every probability incorrectly. Discrimination and calibration are orthogonal. Report both, always.</p><p><strong>(2) Extreme Metrics Almost Always Mean Data Leakage:</strong></p><blockquote>🚨 If any single variable has IV &gt; 0.50, or your model achieves KS &gt; 75 or AUC &gt; 0.95, stop and investigate. These levels are almost impossible in retail credit. You almost certainly have a target variable or post-event feature leaking into your training data.</blockquote><p><strong>(3) No Out-of-Time Validation</strong></p><p>Cross-validation on a single time window does not protect against temporal overfitting. Always hold out a dataset from a <strong>later period</strong> — 6–12 months after your training window. AUC/Gini dropping more than 8–10 points on OOT is a red flag.</p><p><strong>(4) Ignoring Population Drift (PSI)</strong></p><p>PSI = Σ (Actual%ᵢ − Expected%ᵢ) × ln( Actual%ᵢ / Expected%ᵢ )</p><p>PSI &gt; 0.10 signals drift; PSI &gt; 0.25 signals the model needs recalibration or redevelopment.</p><p><strong>(5) Reporting Accuracy on an Imbalanced Dataset</strong></p><p>A model predicting “no default” for everyone achieves 95% accuracy on a 5% default-rate portfolio. Use AUC, KS, or PR-AUC. If someone in a meeting quotes accuracy, politely ask which metric they mean.</p><h3>Conclusion</h3><p>Evaluating a credit risk model is not a single-number exercise. AUC and Gini tell you whether the model ranks borrowers correctly. KS tells you where that separation is strongest. PR-AUC tells you whether the model actually finds defaults without being flattered by the non-default majority. Brier Score and Log-Loss tell you whether the probabilities are trustworthy for reserve calculations. IV helps you build the model with the right features. Capture Rate translates model quality into business value.</p><blockquote>Understanding what each metric measures — and what it misses — is what separates a rigorous quantitative analyst from one who stops at the AUC headline.</blockquote><p>The Python functions in this guide are production-ready. Package them into a single ModelEvaluator class, run them at development, OOT validation, and quarterly monitoring - and you will have a validation framework that satisfies CECL, IFRS 9, and Basel IV requirements while actually catching models that look good on paper but fail in the real world.</p><p><em>Tags: Credit Risk · Machine Learning · AUC · Gini · KS Statistic · PR-AUC · Brier Score · Model Validation · CECL · Python · Data Science</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fdca30f62cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>