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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
===============================================================================
|
| 3 |
+
KENDİ YÖNTEMİMİZİ TEST ETME: "Bizim bölme de şişiriyor mu?"
|
| 4 |
+
===============================================================================
|
| 5 |
+
|
| 6 |
+
SORU: Walk-forward validasyon gerçek dünyanın simülasyonudur.
|
| 7 |
+
Hiçbir bölme stratejisi ondan daha gerçekçi olamaz.
|
| 8 |
+
O zaman her stratejinin walk-forward'a yakınlığı = dürüstlük derecesi.
|
| 9 |
+
|
| 10 |
+
TEST: Her stratejinin F1'ini walk-forward F1 ile karşılaştır.
|
| 11 |
+
- Yakın (±%10) = dürüst tahmin
|
| 12 |
+
- Çok üstünde (>%15) = şişirilmiş
|
| 13 |
+
- Çok altında (<-%15) = aşırı pesimist
|
| 14 |
+
===============================================================================
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import os, json
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
|
| 21 |
+
import matplotlib
|
| 22 |
+
matplotlib.use('Agg')
|
| 23 |
+
import matplotlib.pyplot as plt
|
| 24 |
+
import seaborn as sns
|
| 25 |
+
|
| 26 |
+
from sklearn.preprocessing import StandardScaler
|
| 27 |
+
from sklearn.metrics import f1_score, roc_auc_score
|
| 28 |
+
import lightgbm as lgb
|
| 29 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 30 |
+
import xgboost as xgb
|
| 31 |
+
|
| 32 |
+
import warnings
|
| 33 |
+
warnings.filterwarnings('ignore')
|
| 34 |
+
np.random.seed(42)
|
| 35 |
+
|
| 36 |
+
FIGDIR = '/app/figures_proof'
|
| 37 |
+
OUTDIR = '/app/results_proof'
|
| 38 |
+
|
| 39 |
+
# ─── VERİ YÜKLEME ───
|
| 40 |
+
feat_df = pd.read_csv('/app/data/elliptic_txs_features.csv', header=None)
|
| 41 |
+
class_df = pd.read_csv('/app/data/elliptic_txs_classes.csv')
|
| 42 |
+
timesteps = feat_df.iloc[:, 1].values.astype(int)
|
| 43 |
+
features = feat_df.iloc[:, 2:].values.astype(np.float32)
|
| 44 |
+
label_map = {'1': 1, '2': 0, 'unknown': -1}
|
| 45 |
+
labels = np.array([label_map[str(c)] for c in class_df['class'].values])
|
| 46 |
+
labeled_mask = labels >= 0
|
| 47 |
+
X = features[labeled_mask]
|
| 48 |
+
y = labels[labeled_mask]
|
| 49 |
+
ts = timesteps[labeled_mask]
|
| 50 |
+
|
| 51 |
+
def train_eval(X_tr, y_tr, X_te, y_te, model_type='lgbm'):
|
| 52 |
+
scaler = StandardScaler()
|
| 53 |
+
X_tr_s = scaler.fit_transform(X_tr)
|
| 54 |
+
X_te_s = scaler.transform(X_te)
|
| 55 |
+
if model_type == 'lgbm':
|
| 56 |
+
m = lgb.LGBMClassifier(n_estimators=300, max_depth=10, scale_pos_weight=10, random_state=42, n_jobs=-1, verbose=-1)
|
| 57 |
+
elif model_type == 'rf':
|
| 58 |
+
m = RandomForestClassifier(n_estimators=300, max_depth=15, class_weight='balanced', random_state=42, n_jobs=-1)
|
| 59 |
+
elif model_type == 'xgb':
|
| 60 |
+
m = xgb.XGBClassifier(n_estimators=300, max_depth=8, scale_pos_weight=10, random_state=42, n_jobs=-1, verbosity=0)
|
| 61 |
+
m.fit(X_tr_s, y_tr)
|
| 62 |
+
pred = m.predict(X_te_s)
|
| 63 |
+
return f1_score(y_te, pred, zero_division=0)
|
| 64 |
+
|
| 65 |
+
# ─── WALK-FORWARD (ALTIN STANDART) ───
|
| 66 |
+
print("=" * 70)
|
| 67 |
+
print("WALK-FORWARD VALİDASYON (ALTIN STANDART)")
|
| 68 |
+
print("=" * 70)
|
| 69 |
+
|
| 70 |
+
wf_results_all = {}
|
| 71 |
+
for model_type, model_name in [('lgbm', 'LightGBM'), ('rf', 'Random Forest'), ('xgb', 'XGBoost')]:
|
| 72 |
+
wf_f1s = []
|
| 73 |
+
for test_start in range(10, 49, 3):
|
| 74 |
+
tr_mask = ts < test_start
|
| 75 |
+
te_mask = (ts >= test_start) & (ts < test_start + 3)
|
| 76 |
+
if tr_mask.sum() < 50 or te_mask.sum() < 10 or len(np.unique(y[te_mask])) < 2:
|
| 77 |
+
continue
|
| 78 |
+
f1 = train_eval(X[tr_mask], y[tr_mask], X[te_mask], y[te_mask], model_type)
|
| 79 |
+
wf_f1s.append(f1)
|
| 80 |
+
wf_avg = np.mean(wf_f1s)
|
| 81 |
+
wf_results_all[model_name] = wf_avg
|
| 82 |
+
print(f" {model_name}: Walk-Forward ortalama F1 = {wf_avg:.4f}")
|
| 83 |
+
|
| 84 |
+
# ─── ÖNCEKİ SONUÇLARI YÜKLE ───
|
| 85 |
+
topo_results = pd.read_csv('/app/results_topo/all_results.csv')
|
| 86 |
+
|
| 87 |
+
# ─── KARŞILAŞTIRMA TABLOSU ───
|
| 88 |
+
print("\n" + "=" * 70)
|
| 89 |
+
print("HER STRATEJİNİN WALK-FORWARD'A YAKINLIĞI")
|
| 90 |
+
print("=" * 70)
|
| 91 |
+
|
| 92 |
+
comparison_data = []
|
| 93 |
+
for model_name in ['LightGBM', 'Random Forest', 'XGBoost']:
|
| 94 |
+
wf_f1 = wf_results_all[model_name]
|
| 95 |
+
print(f"\n {model_name} (Walk-Forward F1 = {wf_f1:.4f}):")
|
| 96 |
+
|
| 97 |
+
for _, row in topo_results[topo_results['model'] == model_name].iterrows():
|
| 98 |
+
strat = row['strategy']
|
| 99 |
+
f1 = row['f1']
|
| 100 |
+
diff = f1 - wf_f1
|
| 101 |
+
pct = (diff / wf_f1) * 100
|
| 102 |
+
abs_pct = abs(pct)
|
| 103 |
+
|
| 104 |
+
if abs_pct < 10:
|
| 105 |
+
durum = 'DÜRÜST ✓'
|
| 106 |
+
elif pct > 15:
|
| 107 |
+
durum = 'ŞİŞİRİYOR 🔴'
|
| 108 |
+
elif pct > 10:
|
| 109 |
+
durum = 'HAFİF YÜKSEK ⚠️'
|
| 110 |
+
elif pct < -15:
|
| 111 |
+
durum = 'ÇOK PESİMİST'
|
| 112 |
+
else:
|
| 113 |
+
durum = 'HAFİF DÜŞÜK'
|
| 114 |
+
|
| 115 |
+
comparison_data.append({
|
| 116 |
+
'Model': model_name, 'Strateji': strat,
|
| 117 |
+
'F1': f1, 'WF_F1': wf_f1, 'Fark': diff, 'Pct': pct, 'Durum': durum
|
| 118 |
+
})
|
| 119 |
+
print(f" {strat:<30s} F1={f1:.4f} fark={diff:+.4f} ({pct:+.1f}%) {durum}")
|
| 120 |
+
|
| 121 |
+
comp_df = pd.DataFrame(comparison_data)
|
| 122 |
+
|
| 123 |
+
# ─── SONUÇ ───
|
| 124 |
+
print("\n" + "=" * 70)
|
| 125 |
+
print("SONUÇ")
|
| 126 |
+
print("=" * 70)
|
| 127 |
+
|
| 128 |
+
# Her stratejinin ortalama sapması
|
| 129 |
+
print("\nStratejilerin walk-forward'a ortalama sapması (tüm modeller):")
|
| 130 |
+
for strat in comp_df['Strateji'].unique():
|
| 131 |
+
subset = comp_df[comp_df['Strateji'] == strat]
|
| 132 |
+
avg_pct = subset['Pct'].mean()
|
| 133 |
+
print(f" {strat:<30s}: ortalama {avg_pct:+.1f}%")
|
| 134 |
+
|
| 135 |
+
# ─── FİGÜR ───
|
| 136 |
+
print("\nFİGÜR OLUŞTURULUYOR...")
|
| 137 |
+
sns.set_theme(style='whitegrid', font_scale=1.1)
|
| 138 |
+
|
| 139 |
+
fig, ax = plt.subplots(figsize=(16, 9))
|
| 140 |
+
|
| 141 |
+
strategies_order = ['Rastgele', 'Kronolojik', 'Topolojik Kırılma (Bizim)', 'Kayan Pencere', 'Düşmanca-Kriz']
|
| 142 |
+
models_order = ['LightGBM', 'Random Forest', 'XGBoost']
|
| 143 |
+
colors = {'LightGBM': '#4ECDC4', 'Random Forest': '#45B7D1', 'XGBoost': '#96CEB4'}
|
| 144 |
+
x = np.arange(len(strategies_order))
|
| 145 |
+
width = 0.22
|
| 146 |
+
|
| 147 |
+
for i, model_name in enumerate(models_order):
|
| 148 |
+
wf_f1 = wf_results_all[model_name]
|
| 149 |
+
vals = []
|
| 150 |
+
for strat in strategies_order:
|
| 151 |
+
row = comp_df[(comp_df['Model'] == model_name) & (comp_df['Strateji'] == strat)]
|
| 152 |
+
vals.append(row['F1'].values[0] if len(row) > 0 else 0)
|
| 153 |
+
|
| 154 |
+
bars = ax.bar(x + i * width, vals, width, label=model_name, color=colors[model_name],
|
| 155 |
+
edgecolor='black', linewidth=0.5)
|
| 156 |
+
|
| 157 |
+
# Walk-forward bandı
|
| 158 |
+
wf_avg_all = np.mean(list(wf_results_all.values()))
|
| 159 |
+
wf_min = min(wf_results_all.values())
|
| 160 |
+
wf_max = max(wf_results_all.values())
|
| 161 |
+
ax.axhspan(wf_min * 0.9, wf_max * 1.1, alpha=0.15, color='green', label='Walk-Forward bandı (±%10)')
|
| 162 |
+
ax.axhline(y=wf_avg_all, color='green', linewidth=2, linestyle='--', label=f'Walk-Forward ort. F1={wf_avg_all:.3f}')
|
| 163 |
+
|
| 164 |
+
ax.set_xticks(x + width)
|
| 165 |
+
ax.set_xticklabels(strategies_order, rotation=15, ha='right', fontsize=11)
|
| 166 |
+
ax.set_ylabel('Illicit F1 Score', fontsize=13)
|
| 167 |
+
ax.set_title('Her Bölme Stratejisinin Walk-Forward\'a (Gerçek Dünya) Yakınlığı\n'
|
| 168 |
+
'Yeşil bant içinde = dürüst tahmin, üstünde = şişirilmiş', fontsize=14, fontweight='bold')
|
| 169 |
+
ax.legend(fontsize=10, loc='upper right')
|
| 170 |
+
ax.set_ylim(0, 1.1)
|
| 171 |
+
ax.grid(axis='y', alpha=0.3)
|
| 172 |
+
|
| 173 |
+
plt.tight_layout()
|
| 174 |
+
plt.savefig(f'{FIGDIR}/fig6_honesty_test.png', dpi=150, bbox_inches='tight')
|
| 175 |
+
plt.close()
|
| 176 |
+
print(" ✓ Figür 6: Dürüstlük Testi")
|
| 177 |
+
|
| 178 |
+
# JSON kaydet
|
| 179 |
+
comp_df.to_csv(f'{OUTDIR}/honesty_comparison.csv', index=False)
|
| 180 |
+
with open(f'{OUTDIR}/walk_forward_by_model.json', 'w') as f:
|
| 181 |
+
json.dump({k: float(v) for k, v in wf_results_all.items()}, f, indent=2)
|
| 182 |
+
|
| 183 |
+
print("\n✓ Tamamlandı!")
|