evanslur commited on
Commit
aa0b39d
·
1 Parent(s): 52586a7

modify files

Browse files
31 Indobert-base-p1_without_law_with_svr.py CHANGED
@@ -7,6 +7,7 @@
7
  import os
8
  import re
9
  import json
 
10
  import zipfile
11
  import shutil
12
  import tempfile
@@ -258,9 +259,18 @@ tokenizer.save_pretrained(OUTPUT_DIR)
258
 
259
 
260
  # ======================================================
261
- # 6. Evaluation
262
  # ======================================================
263
- print("\n📊 Evaluating on Test Set...")
 
 
 
 
 
 
 
 
 
264
 
265
  # Predict (Output is scaled)
266
  preds_scaled = svr_pipeline.predict(X_test)
@@ -272,50 +282,268 @@ y_true_days = label_scaler.inverse_transform(y_test_scaled.reshape(-1, 1)).flatt
272
  # Clip negatives (sentences can't be negative)
273
  preds_days = np.maximum(preds_days, 0)
274
 
275
- # Metrics
276
  mse = mean_squared_error(y_true_days, preds_days)
277
  rmse = np.sqrt(mse)
278
  mae = mean_absolute_error(y_true_days, preds_days)
279
  r2 = r2_score(y_true_days, preds_days)
280
 
281
- print("\n🎯 Test Results:")
282
- print(f" RMSE: {rmse:,.2f} days")
283
- print(f" MAE: {mae:,.2f} days")
284
- print(f" R2: {r2:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
- # Save detailed results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  results_df = pd.DataFrame({
288
  'file_name': test_filenames,
289
  'true_label': y_true_days,
290
  'prediction': preds_days,
291
- 'error': np.abs(y_true_days - preds_days)
 
292
  })
293
- results_csv = Path(OUTPUT_DIR) / 'svr_test_predictions.csv'
294
  results_df.to_csv(results_csv, index=False)
295
- print(f"💾 Detailed predictions saved to {results_csv}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
 
297
 
298
  # ======================================================
299
  # 7. Plotting
300
  # ======================================================
301
- print("\n📈 Generating Plots...")
302
- img_dir = Path(OUTPUT_DIR) / 'plots'
303
- img_dir.mkdir(parents=True, exist_ok=True)
304
-
305
- # Scatter Plot
306
- plt.figure(figsize=(8, 8))
307
- plt.scatter(results_df['true_label'], results_df['prediction'], alpha=0.5, color='purple')
308
- lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
309
- plt.plot(lims, lims, '--', color='gray')
310
- plt.xlim(lims)
311
- plt.ylim(lims)
312
- plt.title(f'SVR: True vs Predicted Days (R2={r2:.3f})')
313
- plt.xlabel('True Days')
314
- plt.ylabel('Predicted Days')
315
- plt.grid(True, alpha=0.3)
316
- plt.tight_layout()
317
- plt.savefig(img_dir / 'svr_scatter.png')
318
- print(f"🖼️ Plot saved to {img_dir / 'svr_scatter.png'}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
 
320
 
321
  # ======================================================
 
7
  import os
8
  import re
9
  import json
10
+ import sys
11
  import zipfile
12
  import shutil
13
  import tempfile
 
259
 
260
 
261
  # ======================================================
262
+ # 6. Evaluation (Comprehensive)
263
  # ======================================================
264
+ from sklearn.metrics import (
265
+ mean_squared_error,
266
+ mean_absolute_error,
267
+ r2_score,
268
+ mean_absolute_percentage_error
269
+ )
270
+
271
+ print("\n" + "="*70)
272
+ print("📊 COMPUTING COMPREHENSIVE TEST SET METRICS")
273
+ print("="*70)
274
 
275
  # Predict (Output is scaled)
276
  preds_scaled = svr_pipeline.predict(X_test)
 
282
  # Clip negatives (sentences can't be negative)
283
  preds_days = np.maximum(preds_days, 0)
284
 
285
+ # Basic metrics
286
  mse = mean_squared_error(y_true_days, preds_days)
287
  rmse = np.sqrt(mse)
288
  mae = mean_absolute_error(y_true_days, preds_days)
289
  r2 = r2_score(y_true_days, preds_days)
290
 
291
+ # Additional metrics
292
+ median_ae = np.median(np.abs(y_true_days - preds_days))
293
+ max_error = np.max(np.abs(y_true_days - preds_days))
294
+ min_error = np.min(np.abs(y_true_days - preds_days))
295
+
296
+ # Percentage errors (avoid division by zero)
297
+ mask = y_true_days != 0
298
+ if mask.sum() > 0:
299
+ mape = np.mean(np.abs((y_true_days[mask] - preds_days[mask]) / y_true_days[mask])) * 100
300
+ else:
301
+ mape = float('nan')
302
+
303
+ # Statistics
304
+ pred_mean = np.mean(preds_days)
305
+ pred_std = np.std(preds_days)
306
+ pred_min = np.min(preds_days)
307
+ pred_max = np.max(preds_days)
308
+
309
+ true_mean = np.mean(y_true_days)
310
+ true_std = np.std(y_true_days)
311
+ true_min = np.min(y_true_days)
312
+ true_max = np.max(y_true_days)
313
+
314
+ print("\n🎯 ERROR METRICS:")
315
+ print(f" MSE: {mse:>12,.2f} days²")
316
+ print(f" RMSE: {rmse:>12,.2f} days")
317
+ print(f" MAE: {mae:>12,.2f} days")
318
+ print(f" Median AE: {median_ae:>12,.2f} days")
319
+ print(f" Max Error: {max_error:>12,.2f} days")
320
+ print(f" Min Error: {min_error:>12,.2f} days")
321
+ if not np.isnan(mape):
322
+ print(f" MAPE: {mape:>12,.2f}%")
323
+ print(f" R² Score: {r2:>12,.4f}")
324
+
325
+ print("\n📊 PREDICTION STATISTICS:")
326
+ print(f" Mean: {pred_mean:>12,.2f} days")
327
+ print(f" Std Dev: {pred_std:>12,.2f} days")
328
+ print(f" Min: {pred_min:>12,.2f} days")
329
+ print(f" Max: {pred_max:>12,.2f} days")
330
+
331
+ print("\n📊 TRUE LABEL STATISTICS:")
332
+ print(f" Mean: {true_mean:>12,.2f} days")
333
+ print(f" Std Dev: {true_std:>12,.2f} days")
334
+ print(f" Min: {true_min:>12,.2f} days")
335
+ print(f" Max: {true_max:>12,.2f} days")
336
+
337
+ # Error distribution analysis
338
+ print("\n📉 ERROR DISTRIBUTION:")
339
+ errors = np.abs(y_true_days - preds_days)
340
+ percentiles = [10, 25, 50, 75, 90, 95, 99]
341
+ print(" Percentiles of Absolute Error:")
342
+ for p in percentiles:
343
+ val = np.percentile(errors, p)
344
+ print(f" {p}th percentile: {val:>12,.2f} days")
345
+
346
+ # Accuracy within ranges
347
+ print("\n🎯 ACCURACY WITHIN ERROR RANGES:")
348
+ for threshold in [100, 250, 500, 750, 1000]:
349
+ within = np.sum(errors <= threshold) / len(errors) * 100
350
+ print(f" Within ±{threshold:>4} days: {within:>6.2f}% of samples")
351
 
352
+
353
+ # ======================================================
354
+ # SAVE DETAILED RESULTS
355
+ # ======================================================
356
+ detailed_results = {
357
+ 'error_metrics': {
358
+ 'mse': float(mse),
359
+ 'rmse': float(rmse),
360
+ 'mae': float(mae),
361
+ 'median_ae': float(median_ae),
362
+ 'max_error': float(max_error),
363
+ 'min_error': float(min_error),
364
+ 'mape': float(mape) if not np.isnan(mape) else None,
365
+ 'r2_score': float(r2)
366
+ },
367
+ 'prediction_stats': {
368
+ 'mean': float(pred_mean),
369
+ 'std': float(pred_std),
370
+ 'min': float(pred_min),
371
+ 'max': float(pred_max)
372
+ },
373
+ 'true_label_stats': {
374
+ 'mean': float(true_mean),
375
+ 'std': float(true_std),
376
+ 'min': float(true_min),
377
+ 'max': float(true_max)
378
+ },
379
+ 'error_percentiles': {
380
+ f'p{p}': float(np.percentile(errors, p)) for p in percentiles
381
+ },
382
+ 'accuracy_within_ranges': {
383
+ f'within_{threshold}': float(np.sum(errors <= threshold) / len(errors) * 100)
384
+ for threshold in [100, 250, 500, 750, 1000]
385
+ }
386
+ }
387
+
388
+ results_detailed_file = Path(OUTPUT_DIR) / 'test_results_detailed.json'
389
+ with open(results_detailed_file, 'w') as f:
390
+ json.dump(detailed_results, f, indent=2)
391
+
392
+ print(f"\n💾 Detailed results saved to: {results_detailed_file}")
393
+
394
+ # Save predictions vs true labels CSV
395
  results_df = pd.DataFrame({
396
  'file_name': test_filenames,
397
  'true_label': y_true_days,
398
  'prediction': preds_days,
399
+ 'absolute_error': errors,
400
+ 'percentage_error': np.abs((y_true_days - preds_days) / (y_true_days + 1)) * 100 # +1 to avoid div by 0
401
  })
402
+ results_csv = Path(OUTPUT_DIR) / 'test_predictions.csv'
403
  results_df.to_csv(results_csv, index=False)
404
+ print(f"💾 Predictions CSV saved to: {results_csv}")
405
+
406
+ # Also save a simple inference CSV with filename and predicted value (user-friendly export)
407
+ try:
408
+ # Ensure alignment in case of any mismatch
409
+ n_simple = min(len(test_filenames), len(preds_days))
410
+ simple_df = pd.DataFrame({
411
+ 'filename': test_filenames[:n_simple],
412
+ 'predicted_day_sentece': np.array(preds_days[:n_simple]).flatten()
413
+ })
414
+ simple_results_file = Path(OUTPUT_DIR) / 'test_inference_simple.csv'
415
+ simple_df.to_csv(simple_results_file, index=False)
416
+ print(f"💾 Simple inference CSV saved to: {simple_results_file}")
417
+ except Exception as e:
418
+ print(f"⚠️ Failed to save simple inference CSV: {e}")
419
+
420
+ # ======================================================
421
+ # 🧪 SAMPLE PREDICTIONS DISPLAY
422
+ # ======================================================
423
+ print("\n" + "="*70)
424
+ print("🧪 SAMPLE PREDICTIONS (First 10)")
425
+ print("="*70)
426
+ for i in range(min(10, len(preds_days))):
427
+ fname = test_filenames[i] if i < len(test_filenames) else ''
428
+ true_val = y_true_days[i]
429
+ pred_val = preds_days[i]
430
+ error = abs(true_val - pred_val)
431
+ pct_error = (error / (true_val + 1)) * 100
432
+
433
+ print(f"\nSample {i+1}:")
434
+ print(f" File: {fname}")
435
+ print(f" True: {true_val:>8,.0f} days")
436
+ print(f" Predicted: {pred_val:>8,.0f} days")
437
+ print(f" Error: {error:>8,.0f} days ({pct_error:.1f}%)")
438
+
439
+ print("\n" + "="*70)
440
+ print("✅ COMPREHENSIVE TEST SET EVALUATION COMPLETE!")
441
+ print(f" - {results_detailed_file}")
442
+ print(f" - {results_csv}")
443
+ print(f" - {OUTPUT_DIR}/label_scaler.pkl")
444
+ print(f" - {OUTPUT_DIR}/svr_model.pkl")
445
 
446
 
447
  # ======================================================
448
  # 7. Plotting
449
  # ======================================================
450
+ try:
451
+ print("\n🔍 Generating plots for predictions...")
452
+ img_dir = Path(OUTPUT_DIR) / 'plots'
453
+ img_dir.mkdir(parents=True, exist_ok=True)
454
+
455
+ # Basic scatterplots over sample index
456
+ idx = np.arange(len(results_df))
457
+
458
+ plt.figure(figsize=(12, 4))
459
+ plt.scatter(idx, results_df['true_label'], s=6, alpha=0.6)
460
+ plt.title('Ground truth (true_label) over samples')
461
+ plt.xlabel('Sample index')
462
+ plt.ylabel('Days')
463
+ plt.tight_layout()
464
+ p1 = img_dir / 'scatter_true.png'
465
+ plt.savefig(p1)
466
+ plt.close()
467
+
468
+ plt.figure(figsize=(12, 4))
469
+ plt.scatter(idx, results_df['prediction'], s=6, alpha=0.6, color='orange')
470
+ plt.title('Predictions over samples')
471
+ plt.xlabel('Sample index')
472
+ plt.ylabel('Predicted days')
473
+ plt.tight_layout()
474
+ p2 = img_dir / 'scatter_pred.png'
475
+ plt.savefig(p2)
476
+ plt.close()
477
+
478
+ # True vs Predicted scatter (combination)
479
+ plt.figure(figsize=(6, 6))
480
+ plt.scatter(results_df['true_label'], results_df['prediction'], s=8, alpha=0.5)
481
+ lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
482
+ plt.plot(lims, lims, '--', color='gray')
483
+ plt.xlim(lims)
484
+ plt.ylim(lims)
485
+ plt.xlabel('True days')
486
+ plt.ylabel('Predicted days')
487
+ plt.title('True vs Predicted')
488
+ plt.tight_layout()
489
+ p3 = img_dir / 'scatter_true_vs_pred.png'
490
+ plt.savefig(p3)
491
+ plt.close()
492
+
493
+ print(f"✅ Scatter plots saved: {p1}, {p2}, {p3}")
494
+
495
+ # Merge with test metadata to get crime_category (charge classification)
496
+ try:
497
+ meta_test = pd.read_csv(splits_dir / 'test_split.csv')
498
+ merged = results_df.merge(meta_test[['file_name', 'crime_category']], on='file_name', how='left')
499
+
500
+ # Choose top categories by sample count for plotting (limit to 6)
501
+ top_cats = merged['crime_category'].value_counts().nlargest(6).index.tolist()
502
+
503
+ # Plot distributions (KDE) of true and predicted per category
504
+ for cat in top_cats:
505
+ subset = merged[merged['crime_category'] == cat]
506
+ if len(subset) < 5:
507
+ print(f"Skipping category '{cat}' (only {len(subset)} samples)")
508
+ continue
509
+
510
+ plt.figure(figsize=(8, 4))
511
+ try:
512
+ sns.kdeplot(subset['true_label'], label='true', fill=True)
513
+ except Exception:
514
+ plt.hist(subset['true_label'], bins=30, alpha=0.4, density=True, label='true')
515
+ try:
516
+ sns.kdeplot(subset['prediction'], label='pred', color='orange', fill=True)
517
+ except Exception:
518
+ plt.hist(subset['prediction'], bins=30, alpha=0.4, density=True, label='pred', color='orange')
519
+
520
+ plt.title(f'Distribution for category: {cat}')
521
+ plt.xlabel('Days')
522
+ plt.legend()
523
+ plt.tight_layout()
524
+ fcat = img_dir / f"dist_{re.sub(r'[^a-zA-Z0-9]+','_', cat)[:50]}.png"
525
+ plt.savefig(fcat)
526
+ plt.close()
527
+ print(f" - Saved distribution for '{cat}': {fcat}")
528
+
529
+ # Additionally: combined faceted histograms for top categories
530
+ try:
531
+ combined = merged[merged['crime_category'].isin(top_cats)].copy()
532
+ combined = combined.melt(id_vars=['file_name', 'crime_category'], value_vars=['true_label', 'prediction'], var_name='which', value_name='days')
533
+ g = sns.FacetGrid(combined, col='crime_category', hue='which', sharex=False, sharey=False, col_wrap=3)
534
+ g.map(sns.histplot, 'days', bins=30, alpha=0.6)
535
+ g.add_legend()
536
+ combined_plot = img_dir / 'combined_category_histograms.png'
537
+ plt.tight_layout()
538
+ plt.savefig(combined_plot)
539
+ plt.close()
540
+ print(f"✅ Combined category histograms saved: {combined_plot}")
541
+ except Exception as e:
542
+ print("⚠️ Failed to create combined faceted histograms:", e)
543
+ except Exception as e:
544
+ print("⚠️ Could not load test metadata for per-category plots:", e)
545
+ except Exception as e:
546
+ print("⚠️ Plotting failed:", e)
547
 
548
 
549
  # ======================================================
32 Indobert-base-p1_with_law_with_svr.py CHANGED
@@ -7,6 +7,7 @@
7
  import os
8
  import re
9
  import json
 
10
  import zipfile
11
  import shutil
12
  import tempfile
@@ -258,9 +259,18 @@ tokenizer.save_pretrained(OUTPUT_DIR)
258
 
259
 
260
  # ======================================================
261
- # 6. Evaluation
262
  # ======================================================
263
- print("\n📊 Evaluating on Test Set...")
 
 
 
 
 
 
 
 
 
264
 
265
  # Predict (Output is scaled)
266
  preds_scaled = svr_pipeline.predict(X_test)
@@ -272,50 +282,268 @@ y_true_days = label_scaler.inverse_transform(y_test_scaled.reshape(-1, 1)).flatt
272
  # Clip negatives (sentences can't be negative)
273
  preds_days = np.maximum(preds_days, 0)
274
 
275
- # Metrics
276
  mse = mean_squared_error(y_true_days, preds_days)
277
  rmse = np.sqrt(mse)
278
  mae = mean_absolute_error(y_true_days, preds_days)
279
  r2 = r2_score(y_true_days, preds_days)
280
 
281
- print("\n🎯 Test Results:")
282
- print(f" RMSE: {rmse:,.2f} days")
283
- print(f" MAE: {mae:,.2f} days")
284
- print(f" R2: {r2:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
- # Save detailed results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  results_df = pd.DataFrame({
288
  'file_name': test_filenames,
289
  'true_label': y_true_days,
290
  'prediction': preds_days,
291
- 'error': np.abs(y_true_days - preds_days)
 
292
  })
293
- results_csv = Path(OUTPUT_DIR) / 'svr_test_predictions.csv'
294
  results_df.to_csv(results_csv, index=False)
295
- print(f"💾 Detailed predictions saved to {results_csv}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
 
297
 
298
  # ======================================================
299
  # 7. Plotting
300
  # ======================================================
301
- print("\n📈 Generating Plots...")
302
- img_dir = Path(OUTPUT_DIR) / 'plots'
303
- img_dir.mkdir(parents=True, exist_ok=True)
304
-
305
- # Scatter Plot
306
- plt.figure(figsize=(8, 8))
307
- plt.scatter(results_df['true_label'], results_df['prediction'], alpha=0.5, color='purple')
308
- lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
309
- plt.plot(lims, lims, '--', color='gray')
310
- plt.xlim(lims)
311
- plt.ylim(lims)
312
- plt.title(f'SVR: True vs Predicted Days (R2={r2:.3f})')
313
- plt.xlabel('True Days')
314
- plt.ylabel('Predicted Days')
315
- plt.grid(True, alpha=0.3)
316
- plt.tight_layout()
317
- plt.savefig(img_dir / 'svr_scatter.png')
318
- print(f"🖼️ Plot saved to {img_dir / 'svr_scatter.png'}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
 
320
 
321
  # ======================================================
 
7
  import os
8
  import re
9
  import json
10
+ import sys
11
  import zipfile
12
  import shutil
13
  import tempfile
 
259
 
260
 
261
  # ======================================================
262
+ # 6. Evaluation (Comprehensive)
263
  # ======================================================
264
+ from sklearn.metrics import (
265
+ mean_squared_error,
266
+ mean_absolute_error,
267
+ r2_score,
268
+ mean_absolute_percentage_error
269
+ )
270
+
271
+ print("\n" + "="*70)
272
+ print("📊 COMPUTING COMPREHENSIVE TEST SET METRICS")
273
+ print("="*70)
274
 
275
  # Predict (Output is scaled)
276
  preds_scaled = svr_pipeline.predict(X_test)
 
282
  # Clip negatives (sentences can't be negative)
283
  preds_days = np.maximum(preds_days, 0)
284
 
285
+ # Basic metrics
286
  mse = mean_squared_error(y_true_days, preds_days)
287
  rmse = np.sqrt(mse)
288
  mae = mean_absolute_error(y_true_days, preds_days)
289
  r2 = r2_score(y_true_days, preds_days)
290
 
291
+ # Additional metrics
292
+ median_ae = np.median(np.abs(y_true_days - preds_days))
293
+ max_error = np.max(np.abs(y_true_days - preds_days))
294
+ min_error = np.min(np.abs(y_true_days - preds_days))
295
+
296
+ # Percentage errors (avoid division by zero)
297
+ mask = y_true_days != 0
298
+ if mask.sum() > 0:
299
+ mape = np.mean(np.abs((y_true_days[mask] - preds_days[mask]) / y_true_days[mask])) * 100
300
+ else:
301
+ mape = float('nan')
302
+
303
+ # Statistics
304
+ pred_mean = np.mean(preds_days)
305
+ pred_std = np.std(preds_days)
306
+ pred_min = np.min(preds_days)
307
+ pred_max = np.max(preds_days)
308
+
309
+ true_mean = np.mean(y_true_days)
310
+ true_std = np.std(y_true_days)
311
+ true_min = np.min(y_true_days)
312
+ true_max = np.max(y_true_days)
313
+
314
+ print("\n🎯 ERROR METRICS:")
315
+ print(f" MSE: {mse:>12,.2f} days²")
316
+ print(f" RMSE: {rmse:>12,.2f} days")
317
+ print(f" MAE: {mae:>12,.2f} days")
318
+ print(f" Median AE: {median_ae:>12,.2f} days")
319
+ print(f" Max Error: {max_error:>12,.2f} days")
320
+ print(f" Min Error: {min_error:>12,.2f} days")
321
+ if not np.isnan(mape):
322
+ print(f" MAPE: {mape:>12,.2f}%")
323
+ print(f" R² Score: {r2:>12,.4f}")
324
+
325
+ print("\n📊 PREDICTION STATISTICS:")
326
+ print(f" Mean: {pred_mean:>12,.2f} days")
327
+ print(f" Std Dev: {pred_std:>12,.2f} days")
328
+ print(f" Min: {pred_min:>12,.2f} days")
329
+ print(f" Max: {pred_max:>12,.2f} days")
330
+
331
+ print("\n📊 TRUE LABEL STATISTICS:")
332
+ print(f" Mean: {true_mean:>12,.2f} days")
333
+ print(f" Std Dev: {true_std:>12,.2f} days")
334
+ print(f" Min: {true_min:>12,.2f} days")
335
+ print(f" Max: {true_max:>12,.2f} days")
336
+
337
+ # Error distribution analysis
338
+ print("\n📉 ERROR DISTRIBUTION:")
339
+ errors = np.abs(y_true_days - preds_days)
340
+ percentiles = [10, 25, 50, 75, 90, 95, 99]
341
+ print(" Percentiles of Absolute Error:")
342
+ for p in percentiles:
343
+ val = np.percentile(errors, p)
344
+ print(f" {p}th percentile: {val:>12,.2f} days")
345
+
346
+ # Accuracy within ranges
347
+ print("\n🎯 ACCURACY WITHIN ERROR RANGES:")
348
+ for threshold in [100, 250, 500, 750, 1000]:
349
+ within = np.sum(errors <= threshold) / len(errors) * 100
350
+ print(f" Within ±{threshold:>4} days: {within:>6.2f}% of samples")
351
 
352
+
353
+ # ======================================================
354
+ # SAVE DETAILED RESULTS
355
+ # ======================================================
356
+ detailed_results = {
357
+ 'error_metrics': {
358
+ 'mse': float(mse),
359
+ 'rmse': float(rmse),
360
+ 'mae': float(mae),
361
+ 'median_ae': float(median_ae),
362
+ 'max_error': float(max_error),
363
+ 'min_error': float(min_error),
364
+ 'mape': float(mape) if not np.isnan(mape) else None,
365
+ 'r2_score': float(r2)
366
+ },
367
+ 'prediction_stats': {
368
+ 'mean': float(pred_mean),
369
+ 'std': float(pred_std),
370
+ 'min': float(pred_min),
371
+ 'max': float(pred_max)
372
+ },
373
+ 'true_label_stats': {
374
+ 'mean': float(true_mean),
375
+ 'std': float(true_std),
376
+ 'min': float(true_min),
377
+ 'max': float(true_max)
378
+ },
379
+ 'error_percentiles': {
380
+ f'p{p}': float(np.percentile(errors, p)) for p in percentiles
381
+ },
382
+ 'accuracy_within_ranges': {
383
+ f'within_{threshold}': float(np.sum(errors <= threshold) / len(errors) * 100)
384
+ for threshold in [100, 250, 500, 750, 1000]
385
+ }
386
+ }
387
+
388
+ results_detailed_file = Path(OUTPUT_DIR) / 'test_results_detailed.json'
389
+ with open(results_detailed_file, 'w') as f:
390
+ json.dump(detailed_results, f, indent=2)
391
+
392
+ print(f"\n💾 Detailed results saved to: {results_detailed_file}")
393
+
394
+ # Save predictions vs true labels CSV
395
  results_df = pd.DataFrame({
396
  'file_name': test_filenames,
397
  'true_label': y_true_days,
398
  'prediction': preds_days,
399
+ 'absolute_error': errors,
400
+ 'percentage_error': np.abs((y_true_days - preds_days) / (y_true_days + 1)) * 100 # +1 to avoid div by 0
401
  })
402
+ results_csv = Path(OUTPUT_DIR) / 'test_predictions.csv'
403
  results_df.to_csv(results_csv, index=False)
404
+ print(f"💾 Predictions CSV saved to: {results_csv}")
405
+
406
+ # Also save a simple inference CSV with filename and predicted value (user-friendly export)
407
+ try:
408
+ # Ensure alignment in case of any mismatch
409
+ n_simple = min(len(test_filenames), len(preds_days))
410
+ simple_df = pd.DataFrame({
411
+ 'filename': test_filenames[:n_simple],
412
+ 'predicted_day_sentece': np.array(preds_days[:n_simple]).flatten()
413
+ })
414
+ simple_results_file = Path(OUTPUT_DIR) / 'test_inference_simple.csv'
415
+ simple_df.to_csv(simple_results_file, index=False)
416
+ print(f"💾 Simple inference CSV saved to: {simple_results_file}")
417
+ except Exception as e:
418
+ print(f"⚠️ Failed to save simple inference CSV: {e}")
419
+
420
+ # ======================================================
421
+ # 🧪 SAMPLE PREDICTIONS DISPLAY
422
+ # ======================================================
423
+ print("\n" + "="*70)
424
+ print("🧪 SAMPLE PREDICTIONS (First 10)")
425
+ print("="*70)
426
+ for i in range(min(10, len(preds_days))):
427
+ fname = test_filenames[i] if i < len(test_filenames) else ''
428
+ true_val = y_true_days[i]
429
+ pred_val = preds_days[i]
430
+ error = abs(true_val - pred_val)
431
+ pct_error = (error / (true_val + 1)) * 100
432
+
433
+ print(f"\nSample {i+1}:")
434
+ print(f" File: {fname}")
435
+ print(f" True: {true_val:>8,.0f} days")
436
+ print(f" Predicted: {pred_val:>8,.0f} days")
437
+ print(f" Error: {error:>8,.0f} days ({pct_error:.1f}%)")
438
+
439
+ print("\n" + "="*70)
440
+ print("✅ COMPREHENSIVE TEST SET EVALUATION COMPLETE!")
441
+ print(f" - {results_detailed_file}")
442
+ print(f" - {results_csv}")
443
+ print(f" - {OUTPUT_DIR}/label_scaler.pkl")
444
+ print(f" - {OUTPUT_DIR}/svr_model.pkl")
445
 
446
 
447
  # ======================================================
448
  # 7. Plotting
449
  # ======================================================
450
+ try:
451
+ print("\n🔍 Generating plots for predictions...")
452
+ img_dir = Path(OUTPUT_DIR) / 'plots'
453
+ img_dir.mkdir(parents=True, exist_ok=True)
454
+
455
+ # Basic scatterplots over sample index
456
+ idx = np.arange(len(results_df))
457
+
458
+ plt.figure(figsize=(12, 4))
459
+ plt.scatter(idx, results_df['true_label'], s=6, alpha=0.6)
460
+ plt.title('Ground truth (true_label) over samples')
461
+ plt.xlabel('Sample index')
462
+ plt.ylabel('Days')
463
+ plt.tight_layout()
464
+ p1 = img_dir / 'scatter_true.png'
465
+ plt.savefig(p1)
466
+ plt.close()
467
+
468
+ plt.figure(figsize=(12, 4))
469
+ plt.scatter(idx, results_df['prediction'], s=6, alpha=0.6, color='orange')
470
+ plt.title('Predictions over samples')
471
+ plt.xlabel('Sample index')
472
+ plt.ylabel('Predicted days')
473
+ plt.tight_layout()
474
+ p2 = img_dir / 'scatter_pred.png'
475
+ plt.savefig(p2)
476
+ plt.close()
477
+
478
+ # True vs Predicted scatter (combination)
479
+ plt.figure(figsize=(6, 6))
480
+ plt.scatter(results_df['true_label'], results_df['prediction'], s=8, alpha=0.5)
481
+ lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
482
+ plt.plot(lims, lims, '--', color='gray')
483
+ plt.xlim(lims)
484
+ plt.ylim(lims)
485
+ plt.xlabel('True days')
486
+ plt.ylabel('Predicted days')
487
+ plt.title('True vs Predicted')
488
+ plt.tight_layout()
489
+ p3 = img_dir / 'scatter_true_vs_pred.png'
490
+ plt.savefig(p3)
491
+ plt.close()
492
+
493
+ print(f"✅ Scatter plots saved: {p1}, {p2}, {p3}")
494
+
495
+ # Merge with test metadata to get crime_category (charge classification)
496
+ try:
497
+ meta_test = pd.read_csv(splits_dir / 'test_split.csv')
498
+ merged = results_df.merge(meta_test[['file_name', 'crime_category']], on='file_name', how='left')
499
+
500
+ # Choose top categories by sample count for plotting (limit to 6)
501
+ top_cats = merged['crime_category'].value_counts().nlargest(6).index.tolist()
502
+
503
+ # Plot distributions (KDE) of true and predicted per category
504
+ for cat in top_cats:
505
+ subset = merged[merged['crime_category'] == cat]
506
+ if len(subset) < 5:
507
+ print(f"Skipping category '{cat}' (only {len(subset)} samples)")
508
+ continue
509
+
510
+ plt.figure(figsize=(8, 4))
511
+ try:
512
+ sns.kdeplot(subset['true_label'], label='true', fill=True)
513
+ except Exception:
514
+ plt.hist(subset['true_label'], bins=30, alpha=0.4, density=True, label='true')
515
+ try:
516
+ sns.kdeplot(subset['prediction'], label='pred', color='orange', fill=True)
517
+ except Exception:
518
+ plt.hist(subset['prediction'], bins=30, alpha=0.4, density=True, label='pred', color='orange')
519
+
520
+ plt.title(f'Distribution for category: {cat}')
521
+ plt.xlabel('Days')
522
+ plt.legend()
523
+ plt.tight_layout()
524
+ fcat = img_dir / f"dist_{re.sub(r'[^a-zA-Z0-9]+','_', cat)[:50]}.png"
525
+ plt.savefig(fcat)
526
+ plt.close()
527
+ print(f" - Saved distribution for '{cat}': {fcat}")
528
+
529
+ # Additionally: combined faceted histograms for top categories
530
+ try:
531
+ combined = merged[merged['crime_category'].isin(top_cats)].copy()
532
+ combined = combined.melt(id_vars=['file_name', 'crime_category'], value_vars=['true_label', 'prediction'], var_name='which', value_name='days')
533
+ g = sns.FacetGrid(combined, col='crime_category', hue='which', sharex=False, sharey=False, col_wrap=3)
534
+ g.map(sns.histplot, 'days', bins=30, alpha=0.6)
535
+ g.add_legend()
536
+ combined_plot = img_dir / 'combined_category_histograms.png'
537
+ plt.tight_layout()
538
+ plt.savefig(combined_plot)
539
+ plt.close()
540
+ print(f"✅ Combined category histograms saved: {combined_plot}")
541
+ except Exception as e:
542
+ print("⚠️ Failed to create combined faceted histograms:", e)
543
+ except Exception as e:
544
+ print("⚠️ Could not load test metadata for per-category plots:", e)
545
+ except Exception as e:
546
+ print("⚠️ Plotting failed:", e)
547
 
548
 
549
  # ======================================================
51 Indobert-base-p1_without_law_with_xgboost.py CHANGED
@@ -27,6 +27,29 @@ from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
27
 
28
  # Import XGBoost
29
  import xgboost as xgb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  # ======================================================
32
  # User Configuration
@@ -48,9 +71,15 @@ def set_seed(seed: int):
48
 
49
  set_seed(SEED)
50
 
 
 
 
51
  HF_TOKEN = os.environ.get('HF_TOKEN') # Set HF_TOKEN environment variable
52
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
53
- print(f"Device detected: {device}")
 
 
 
54
 
55
  # ======================================================
56
  # 1. Dataset Download & Prep
@@ -58,7 +87,7 @@ print(f"Device detected: {device}")
58
  REPO_ID = "evanslur/skripsi"
59
  ZIP_FILENAME = "dataset.zip"
60
 
61
- print("Downloading dataset...")
62
  zip_path = hf_hub_download(repo_id=REPO_ID, filename=ZIP_FILENAME, repo_type="dataset", token=HF_TOKEN)
63
 
64
  extract_dir = Path("./colloquial_data")
@@ -111,15 +140,17 @@ def preprocess_text(text):
111
  t = re.sub(r"\s+", ' ', t).strip().lower()
112
  return t
113
 
114
- print('Preprocessing text...')
115
  for split in loaded:
116
  loaded[split] = loaded[split].map(lambda x: {'text': preprocess_text(x['text'])}, num_proc=4)
117
 
 
 
118
  # ======================================================
119
  # 3. Label Scaling
120
  # ======================================================
121
  # Meskipun Tree-Based model tidak wajib scaling, ini membantu normalisasi loss function
122
- print("Fitting StandardScaler...")
123
  scaler = StandardScaler()
124
  train_labels_raw = np.array(loaded['train']['day_sentence']).reshape(-1, 1)
125
  scaler.fit(train_labels_raw)
@@ -128,14 +159,17 @@ Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
128
  with open(Path(OUTPUT_DIR) / 'scaler.pkl', 'wb') as f:
129
  pickle.dump(scaler, f)
130
 
 
 
131
  # ======================================================
132
  # 4. Feature Extraction (IndoBERT)
133
  # ======================================================
134
- print(f"Loading IndoBERT: {MODEL_NAME}")
135
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
136
  encoder = AutoModel.from_pretrained(MODEL_NAME, token=HF_TOKEN)
137
  encoder.to(device)
138
  encoder.eval()
 
139
 
140
  def extract_embeddings(dataset_split, batch_size=32):
141
  all_embeddings = []
@@ -145,7 +179,7 @@ def extract_embeddings(dataset_split, batch_size=32):
145
  # Normalize labels
146
  labels_norm = scaler.transform(np.array(labels).reshape(-1, 1)).flatten()
147
 
148
- print(f"Extracting features for {len(texts)} samples...")
149
  for i in tqdm(range(0, len(texts), batch_size)):
150
  batch_texts = texts[i : i + batch_size]
151
  inputs = tokenizer(batch_texts, padding=True, truncation=True, max_length=MAX_LENGTH, return_tensors="pt").to(device)
@@ -164,11 +198,26 @@ X_test, y_test = extract_embeddings(loaded['test'], BATCH_SIZE)
164
  # ======================================================
165
  # 5. Train XGBoost (Tree Based Model)
166
  # ======================================================
167
- print("\n" + "="*50)
168
- print("🌳 Training XGBoost Regressor...")
169
- print("="*50)
 
 
170
 
171
  # Konfigurasi XGBoost
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  xgb_model = xgb.XGBRegressor(
173
  n_estimators=1000, # Jumlah pohon
174
  learning_rate=0.05, # Kecepatan belajar (makin kecil makin teliti tapi lambat)
@@ -188,10 +237,17 @@ xgb_model.fit(
188
  verbose=100
189
  )
190
 
191
- print("✅ XGBoost Training Completed!")
 
 
 
 
 
 
192
  xgb_model.save_model(Path(OUTPUT_DIR) / "xgboost_model.json")
193
  encoder.save_pretrained(Path(OUTPUT_DIR) / "encoder")
194
  tokenizer.save_pretrained(OUTPUT_DIR)
 
195
 
196
  # ======================================================
197
  # 6. Evaluation
@@ -207,13 +263,37 @@ def evaluate_model(model, X, y_true_norm, scaler, prefix="Test"):
207
  mae = mean_absolute_error(y_true_denorm, preds_denorm)
208
  r2 = r2_score(y_true_denorm, preds_denorm)
209
 
210
- print(f"\n📊 {prefix} Results:")
211
- print(f" RMSE: {rmse:.2f} days")
212
- print(f" MAE: {mae:.2f} days")
213
- print(f" R2: {r2:.4f}")
214
- return preds_denorm, y_true_denorm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
- test_preds, test_true = evaluate_model(xgb_model, X_test, y_test, scaler, prefix="Test")
 
 
 
 
 
 
 
217
 
218
  # ======================================================
219
  # 7. Save Results & Plot
@@ -227,24 +307,152 @@ results_df = pd.DataFrame({
227
 
228
  results_csv = Path(OUTPUT_DIR) / 'xgboost_test_predictions.csv'
229
  results_df.to_csv(results_csv, index=False)
230
- print(f"\n💾 Results saved to {results_csv}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
- # Plot
233
  img_dir = Path(OUTPUT_DIR) / 'plots'
234
  img_dir.mkdir(parents=True, exist_ok=True)
235
- plt.figure(figsize=(6, 6))
236
- plt.scatter(results_df['true_label'], results_df['prediction'], alpha=0.5, color='green')
 
 
237
  lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
238
- plt.plot(lims, lims, '--', color='gray')
239
- plt.title(f'XGBoost: True vs Predicted')
240
- plt.xlabel('True Days')
241
- plt.ylabel('Predicted Days')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  plt.tight_layout()
243
- plt.savefig(img_dir / 'xgboost_scatter.png')
244
- print(f"🖼️ Plot saved to {img_dir}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  # ======================================================
247
- # 8. Inference Function
248
  # ======================================================
249
  def predict_sentence_tree(text):
250
  clean_text = preprocess_text(text)
@@ -258,4 +466,94 @@ def predict_sentence_tree(text):
258
  pred_days = scaler.inverse_transform(pred_norm.reshape(-1, 1))[0][0]
259
  return max(0, pred_days)
260
 
261
- print("\n🔮 Inference ready: predict_sentence_tree('text')")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  # Import XGBoost
29
  import xgboost as xgb
30
+ import logging
31
+ from sklearn.metrics import mean_absolute_percentage_error
32
+
33
+ # ======================================================
34
+ # Logging Setup
35
+ # ======================================================
36
+ def setup_logging(output_dir):
37
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
38
+ log_file = Path(output_dir) / 'training.log'
39
+
40
+ # Remove existing handlers
41
+ for handler in logging.root.handlers[:]:
42
+ logging.root.removeHandler(handler)
43
+
44
+ logging.basicConfig(
45
+ level=logging.INFO,
46
+ format='%(asctime)s - %(levelname)s - %(message)s',
47
+ handlers=[
48
+ logging.FileHandler(log_file, mode='w', encoding='utf-8'),
49
+ logging.StreamHandler()
50
+ ]
51
+ )
52
+ return logging.getLogger(__name__)
53
 
54
  # ======================================================
55
  # User Configuration
 
71
 
72
  set_seed(SEED)
73
 
74
+ # Setup logging
75
+ logger = setup_logging(OUTPUT_DIR)
76
+
77
  HF_TOKEN = os.environ.get('HF_TOKEN') # Set HF_TOKEN environment variable
78
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
79
+ logger.info(f"Device detected: {device}")
80
+ logger.info(f"Model: {MODEL_NAME}")
81
+ logger.info(f"Output directory: {OUTPUT_DIR}")
82
+ logger.info(f"Max length: {MAX_LENGTH}, Batch size: {BATCH_SIZE}, Seed: {SEED}")
83
 
84
  # ======================================================
85
  # 1. Dataset Download & Prep
 
87
  REPO_ID = "evanslur/skripsi"
88
  ZIP_FILENAME = "dataset.zip"
89
 
90
+ logger.info("Downloading dataset...")
91
  zip_path = hf_hub_download(repo_id=REPO_ID, filename=ZIP_FILENAME, repo_type="dataset", token=HF_TOKEN)
92
 
93
  extract_dir = Path("./colloquial_data")
 
140
  t = re.sub(r"\s+", ' ', t).strip().lower()
141
  return t
142
 
143
+ logger.info('Preprocessing text...')
144
  for split in loaded:
145
  loaded[split] = loaded[split].map(lambda x: {'text': preprocess_text(x['text'])}, num_proc=4)
146
 
147
+ logger.info(f"Dataset loaded - Train: {len(loaded['train'])}, Val: {len(loaded['validation'])}, Test: {len(loaded['test'])}")
148
+
149
  # ======================================================
150
  # 3. Label Scaling
151
  # ======================================================
152
  # Meskipun Tree-Based model tidak wajib scaling, ini membantu normalisasi loss function
153
+ logger.info("Fitting StandardScaler...")
154
  scaler = StandardScaler()
155
  train_labels_raw = np.array(loaded['train']['day_sentence']).reshape(-1, 1)
156
  scaler.fit(train_labels_raw)
 
159
  with open(Path(OUTPUT_DIR) / 'scaler.pkl', 'wb') as f:
160
  pickle.dump(scaler, f)
161
 
162
+ logger.info(f"Scaler fitted: mean={scaler.mean_[0]:.2f}, std={scaler.scale_[0]:.2f}")
163
+
164
  # ======================================================
165
  # 4. Feature Extraction (IndoBERT)
166
  # ======================================================
167
+ logger.info(f"Loading IndoBERT: {MODEL_NAME}")
168
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
169
  encoder = AutoModel.from_pretrained(MODEL_NAME, token=HF_TOKEN)
170
  encoder.to(device)
171
  encoder.eval()
172
+ logger.info("IndoBERT encoder loaded successfully")
173
 
174
  def extract_embeddings(dataset_split, batch_size=32):
175
  all_embeddings = []
 
179
  # Normalize labels
180
  labels_norm = scaler.transform(np.array(labels).reshape(-1, 1)).flatten()
181
 
182
+ logger.info(f"Extracting features for {len(texts)} samples...")
183
  for i in tqdm(range(0, len(texts), batch_size)):
184
  batch_texts = texts[i : i + batch_size]
185
  inputs = tokenizer(batch_texts, padding=True, truncation=True, max_length=MAX_LENGTH, return_tensors="pt").to(device)
 
198
  # ======================================================
199
  # 5. Train XGBoost (Tree Based Model)
200
  # ======================================================
201
+ logger.info("\n" + "="*50)
202
+ logger.info("🌳 Training XGBoost Regressor...")
203
+ logger.info("="*50)
204
+ logger.info(f"Feature dimension: {X_train.shape[1]}")
205
+ logger.info(f"Training samples: {X_train.shape[0]}, Validation samples: {X_val.shape[0]}, Test samples: {X_test.shape[0]}")
206
 
207
  # Konfigurasi XGBoost
208
+ xgb_params = {
209
+ 'n_estimators': 1000,
210
+ 'learning_rate': 0.05,
211
+ 'max_depth': 6,
212
+ 'subsample': 0.8,
213
+ 'colsample_bytree': 0.8,
214
+ 'objective': 'reg:squarederror',
215
+ 'n_jobs': -1,
216
+ 'random_state': SEED,
217
+ 'early_stopping_rounds': 50
218
+ }
219
+ logger.info(f"XGBoost parameters: {xgb_params}")
220
+
221
  xgb_model = xgb.XGBRegressor(
222
  n_estimators=1000, # Jumlah pohon
223
  learning_rate=0.05, # Kecepatan belajar (makin kecil makin teliti tapi lambat)
 
237
  verbose=100
238
  )
239
 
240
+ logger.info("✅ XGBoost Training Completed!")
241
+ logger.info(f"Best iteration: {xgb_model.best_iteration}")
242
+ logger.info(f"Best score: {xgb_model.best_score:.6f}")
243
+
244
+ # Get training history
245
+ evals_result = xgb_model.evals_result()
246
+
247
  xgb_model.save_model(Path(OUTPUT_DIR) / "xgboost_model.json")
248
  encoder.save_pretrained(Path(OUTPUT_DIR) / "encoder")
249
  tokenizer.save_pretrained(OUTPUT_DIR)
250
+ logger.info(f"Model saved to {OUTPUT_DIR}")
251
 
252
  # ======================================================
253
  # 6. Evaluation
 
263
  mae = mean_absolute_error(y_true_denorm, preds_denorm)
264
  r2 = r2_score(y_true_denorm, preds_denorm)
265
 
266
+ # Additional metrics
267
+ median_ae = np.median(np.abs(y_true_denorm - preds_denorm))
268
+ max_error = np.max(np.abs(y_true_denorm - preds_denorm))
269
+
270
+ # MAPE (avoid division by zero)
271
+ mask = y_true_denorm != 0
272
+ if mask.sum() > 0:
273
+ mape = mean_absolute_percentage_error(y_true_denorm[mask], preds_denorm[mask]) * 100
274
+ else:
275
+ mape = np.nan
276
+
277
+ logger.info(f"\n📊 {prefix} Results:")
278
+ logger.info(f" MSE: {mse:.2f} days²")
279
+ logger.info(f" RMSE: {rmse:.2f} days")
280
+ logger.info(f" MAE: {mae:.2f} days")
281
+ logger.info(f" Median AE: {median_ae:.2f} days")
282
+ logger.info(f" Max Error: {max_error:.2f} days")
283
+ logger.info(f" R2: {r2:.4f}")
284
+ if not np.isnan(mape):
285
+ logger.info(f" MAPE: {mape:.2f}%")
286
+
287
+ return preds_denorm, y_true_denorm, {'mse': mse, 'rmse': rmse, 'mae': mae, 'median_ae': median_ae, 'max_error': max_error, 'r2': r2, 'mape': mape}
288
 
289
+ # Evaluate all splits
290
+ logger.info("\n" + "="*50)
291
+ logger.info("📊 Evaluating on all splits...")
292
+ logger.info("="*50)
293
+
294
+ train_preds, train_true, train_metrics = evaluate_model(xgb_model, X_train, y_train, scaler, prefix="Train")
295
+ val_preds, val_true, val_metrics = evaluate_model(xgb_model, X_val, y_val, scaler, prefix="Validation")
296
+ test_preds, test_true, test_metrics = evaluate_model(xgb_model, X_test, y_test, scaler, prefix="Test")
297
 
298
  # ======================================================
299
  # 7. Save Results & Plot
 
307
 
308
  results_csv = Path(OUTPUT_DIR) / 'xgboost_test_predictions.csv'
309
  results_df.to_csv(results_csv, index=False)
310
+ logger.info(f"\n💾 Results saved to {results_csv}")
311
+
312
+ # Save detailed results JSON
313
+ detailed_results = {
314
+ 'model': 'XGBoost',
315
+ 'encoder': MODEL_NAME,
316
+ 'dataset': 'colloquial (without law)',
317
+ 'xgb_params': xgb_params,
318
+ 'best_iteration': int(xgb_model.best_iteration),
319
+ 'best_score': float(xgb_model.best_score),
320
+ 'train_metrics': {k: float(v) if not np.isnan(v) else None for k, v in train_metrics.items()},
321
+ 'val_metrics': {k: float(v) if not np.isnan(v) else None for k, v in val_metrics.items()},
322
+ 'test_metrics': {k: float(v) if not np.isnan(v) else None for k, v in test_metrics.items()},
323
+ 'prediction_stats': {
324
+ 'mean': float(np.mean(test_preds)),
325
+ 'std': float(np.std(test_preds)),
326
+ 'min': float(np.min(test_preds)),
327
+ 'max': float(np.max(test_preds))
328
+ },
329
+ 'true_label_stats': {
330
+ 'mean': float(np.mean(test_true)),
331
+ 'std': float(np.std(test_true)),
332
+ 'min': float(np.min(test_true)),
333
+ 'max': float(np.max(test_true))
334
+ },
335
+ 'error_percentiles': {
336
+ f'p{p}': float(np.percentile(results_df['error'], p)) for p in [10, 25, 50, 75, 90, 95, 99]
337
+ },
338
+ 'accuracy_within_ranges': {
339
+ f'within_{threshold}': float(np.sum(results_df['error'] <= threshold) / len(results_df) * 100)
340
+ for threshold in [100, 250, 500, 750, 1000]
341
+ }
342
+ }
343
+
344
+ with open(Path(OUTPUT_DIR) / 'test_results_detailed.json', 'w') as f:
345
+ json.dump(detailed_results, f, indent=2)
346
+ logger.info(f"Detailed results saved to {Path(OUTPUT_DIR) / 'test_results_detailed.json'}")
347
+
348
+ # ======================================================
349
+ # 8. Plots
350
+ # ======================================================
351
+ logger.info("\n" + "="*50)
352
+ logger.info("🖼️ Generating plots...")
353
+ logger.info("="*50)
354
 
 
355
  img_dir = Path(OUTPUT_DIR) / 'plots'
356
  img_dir.mkdir(parents=True, exist_ok=True)
357
+
358
+ # Plot 1: Scatter plot - True vs Predicted
359
+ plt.figure(figsize=(8, 8))
360
+ plt.scatter(results_df['true_label'], results_df['prediction'], alpha=0.5, color='green', edgecolors='none', s=30)
361
  lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
362
+ plt.plot(lims, lims, '--', color='red', linewidth=2, label='Perfect Prediction')
363
+ plt.title(f'XGBoost: True vs Predicted\nRMSE={test_metrics["rmse"]:.2f}, MAE={test_metrics["mae"]:.2f}, R²={test_metrics["r2"]:.4f}', fontsize=12)
364
+ plt.xlabel('True Days', fontsize=11)
365
+ plt.ylabel('Predicted Days', fontsize=11)
366
+ plt.legend()
367
+ plt.grid(True, alpha=0.3)
368
+ plt.tight_layout()
369
+ plt.savefig(img_dir / 'scatter_true_vs_predicted.png', dpi=150)
370
+ plt.close()
371
+ logger.info(f" Saved: scatter_true_vs_predicted.png")
372
+
373
+ # Plot 2: Residual Plot
374
+ plt.figure(figsize=(10, 6))
375
+ residuals = test_preds - test_true
376
+ plt.scatter(test_true, residuals, alpha=0.5, color='blue', edgecolors='none', s=30)
377
+ plt.axhline(y=0, color='red', linestyle='--', linewidth=2)
378
+ plt.title('Residual Plot: Predicted - True', fontsize=12)
379
+ plt.xlabel('True Days', fontsize=11)
380
+ plt.ylabel('Residual (Predicted - True)', fontsize=11)
381
+ plt.grid(True, alpha=0.3)
382
+ plt.tight_layout()
383
+ plt.savefig(img_dir / 'residual_plot.png', dpi=150)
384
+ plt.close()
385
+ logger.info(f" Saved: residual_plot.png")
386
+
387
+ # Plot 3: Error Distribution Histogram
388
+ plt.figure(figsize=(10, 6))
389
+ plt.hist(results_df['error'], bins=50, color='steelblue', edgecolor='white', alpha=0.8)
390
+ plt.axvline(x=test_metrics['mae'], color='red', linestyle='--', linewidth=2, label=f'MAE = {test_metrics["mae"]:.2f}')
391
+ plt.axvline(x=test_metrics['median_ae'], color='orange', linestyle='--', linewidth=2, label=f'Median AE = {test_metrics["median_ae"]:.2f}')
392
+ plt.title('Distribution of Absolute Errors', fontsize=12)
393
+ plt.xlabel('Absolute Error (Days)', fontsize=11)
394
+ plt.ylabel('Frequency', fontsize=11)
395
+ plt.legend()
396
+ plt.grid(True, alpha=0.3)
397
+ plt.tight_layout()
398
+ plt.savefig(img_dir / 'error_distribution.png', dpi=150)
399
+ plt.close()
400
+ logger.info(f" Saved: error_distribution.png")
401
+
402
+ # Plot 4: Training Curve (XGBoost Loss)
403
+ if evals_result:
404
+ plt.figure(figsize=(10, 6))
405
+ train_rmse = evals_result['validation_0']['rmse']
406
+ val_rmse = evals_result['validation_1']['rmse']
407
+ epochs = range(1, len(train_rmse) + 1)
408
+ plt.plot(epochs, train_rmse, 'b-', label='Train RMSE', linewidth=2)
409
+ plt.plot(epochs, val_rmse, 'r-', label='Validation RMSE', linewidth=2)
410
+ plt.axvline(x=xgb_model.best_iteration, color='green', linestyle='--', linewidth=1.5, label=f'Best iteration: {xgb_model.best_iteration}')
411
+ plt.title('XGBoost Training Curve', fontsize=12)
412
+ plt.xlabel('Boosting Round', fontsize=11)
413
+ plt.ylabel('RMSE (Normalized)', fontsize=11)
414
+ plt.legend()
415
+ plt.grid(True, alpha=0.3)
416
+ plt.tight_layout()
417
+ plt.savefig(img_dir / 'training_curve.png', dpi=150)
418
+ plt.close()
419
+ logger.info(f" Saved: training_curve.png")
420
+
421
+ # Plot 5: Box plot of errors by label range
422
+ plt.figure(figsize=(12, 6))
423
+ bins = [0, 365, 730, 1460, 2920, float('inf')] # 0-1yr, 1-2yr, 2-4yr, 4-8yr, 8yr+
424
+ labels_cat = ['0-1 year', '1-2 years', '2-4 years', '4-8 years', '8+ years']
425
+ results_df['label_category'] = pd.cut(results_df['true_label'], bins=bins, labels=labels_cat)
426
+ sns.boxplot(x='label_category', y='error', data=results_df, palette='viridis')
427
+ plt.title('Error Distribution by Sentence Length Category', fontsize=12)
428
+ plt.xlabel('True Sentence Category', fontsize=11)
429
+ plt.ylabel('Absolute Error (Days)', fontsize=11)
430
+ plt.xticks(rotation=15)
431
+ plt.grid(True, alpha=0.3, axis='y')
432
  plt.tight_layout()
433
+ plt.savefig(img_dir / 'error_by_category_boxplot.png', dpi=150)
434
+ plt.close()
435
+ logger.info(f" Saved: error_by_category_boxplot.png")
436
+
437
+ # Plot 6: Feature Importance (Top 20)
438
+ plt.figure(figsize=(10, 8))
439
+ importances = xgb_model.feature_importances_
440
+ top_k = 20
441
+ top_indices = np.argsort(importances)[-top_k:][::-1]
442
+ plt.barh(range(top_k), importances[top_indices], color='teal')
443
+ plt.yticks(range(top_k), [f'Feature {i}' for i in top_indices])
444
+ plt.xlabel('Importance', fontsize=11)
445
+ plt.title(f'Top {top_k} Feature Importances (XGBoost)', fontsize=12)
446
+ plt.gca().invert_yaxis()
447
+ plt.tight_layout()
448
+ plt.savefig(img_dir / 'feature_importance.png', dpi=150)
449
+ plt.close()
450
+ logger.info(f" Saved: feature_importance.png")
451
+
452
+ logger.info(f"🖼️ All plots saved to {img_dir}")
453
 
454
  # ======================================================
455
+ # 9. Inference Function
456
  # ======================================================
457
  def predict_sentence_tree(text):
458
  clean_text = preprocess_text(text)
 
466
  pred_days = scaler.inverse_transform(pred_norm.reshape(-1, 1))[0][0]
467
  return max(0, pred_days)
468
 
469
+ logger.info("\n🔮 Inference ready: predict_sentence_tree('text')")
470
+
471
+ # ======================================================
472
+ # 10. Final Summary
473
+ # ======================================================
474
+ logger.info("\n" + "="*70)
475
+ logger.info("📈 TEST SET METRICS (Original Scale - Days)")
476
+ logger.info("="*70)
477
+
478
+ # Extract metrics
479
+ mse = test_metrics['mse']
480
+ rmse = test_metrics['rmse']
481
+ mae = test_metrics['mae']
482
+ median_ae = test_metrics['median_ae']
483
+ max_error = test_metrics['max_error']
484
+ r2 = test_metrics['r2']
485
+ mape = test_metrics.get('mape', np.nan)
486
+ min_error = np.min(results_df['error'])
487
+
488
+ # Statistics
489
+ pred_mean = np.mean(test_preds)
490
+ pred_std = np.std(test_preds)
491
+ pred_min = np.min(test_preds)
492
+ pred_max = np.max(test_preds)
493
+
494
+ true_mean = np.mean(test_true)
495
+ true_std = np.std(test_true)
496
+ true_min = np.min(test_true)
497
+ true_max = np.max(test_true)
498
+
499
+ logger.info("\n🎯 ERROR METRICS:")
500
+ logger.info(f" MSE: {mse:>12,.2f} days²")
501
+ logger.info(f" RMSE: {rmse:>12,.2f} days")
502
+ logger.info(f" MAE: {mae:>12,.2f} days")
503
+ logger.info(f" Median AE: {median_ae:>12,.2f} days")
504
+ logger.info(f" Max Error: {max_error:>12,.2f} days")
505
+ logger.info(f" Min Error: {min_error:>12,.2f} days")
506
+ if not np.isnan(mape):
507
+ logger.info(f" MAPE: {mape:>12,.2f} %")
508
+ logger.info(f" R² Score: {r2:>12,.4f}")
509
+
510
+ logger.info("\n📊 PREDICTION STATISTICS:")
511
+ logger.info(f" Mean: {pred_mean:>12,.2f} days")
512
+ logger.info(f" Std Dev: {pred_std:>12,.2f} days")
513
+ logger.info(f" Min: {pred_min:>12,.2f} days")
514
+ logger.info(f" Max: {pred_max:>12,.2f} days")
515
+
516
+ logger.info("\n📊 TRUE LABEL STATISTICS:")
517
+ logger.info(f" Mean: {true_mean:>12,.2f} days")
518
+ logger.info(f" Std Dev: {true_std:>12,.2f} days")
519
+ logger.info(f" Min: {true_min:>12,.2f} days")
520
+ logger.info(f" Max: {true_max:>12,.2f} days")
521
+
522
+ # Error distribution analysis
523
+ logger.info("\n📉 ERROR DISTRIBUTION:")
524
+ percentiles = [10, 25, 50, 75, 90, 95, 99]
525
+ logger.info(" Percentiles of Absolute Error:")
526
+ for p in percentiles:
527
+ perc_val = np.percentile(results_df['error'], p)
528
+ logger.info(f" {p}th percentile: {perc_val:>12,.2f} days")
529
+
530
+ # Accuracy within ranges
531
+ logger.info("\n🎯 ACCURACY WITHIN ERROR RANGES:")
532
+ for threshold in [100, 250, 500, 750, 1000]:
533
+ acc = np.sum(results_df['error'] <= threshold) / len(results_df) * 100
534
+ logger.info(f" Within {threshold:>4} days: {acc:>12.2f}%")
535
+
536
+ # Sample predictions
537
+ logger.info("\n" + "="*70)
538
+ logger.info("🧪 SAMPLE PREDICTIONS (First 10)")
539
+ logger.info("="*70)
540
+ for i in range(min(10, len(results_df))):
541
+ row = results_df.iloc[i]
542
+ logger.info(f"Sample {i+1}:")
543
+ logger.info(f" File: {row['file_name']}")
544
+ logger.info(f" True: {row['true_label']:.2f} days")
545
+ logger.info(f" Pred: {row['prediction']:.2f} days")
546
+ logger.info(f" Diff: {row['error']:.2f} days")
547
+ logger.info("-" * 30)
548
+
549
+ logger.info("\n" + "="*70)
550
+ logger.info("✅ TRAINING AND EVALUATION COMPLETE!")
551
+ logger.info("="*70)
552
+ logger.info(f"\nOutput files:")
553
+ logger.info(f" - Model: {Path(OUTPUT_DIR) / 'xgboost_model.json'}")
554
+ logger.info(f" - Encoder: {Path(OUTPUT_DIR) / 'encoder'}")
555
+ logger.info(f" - Scaler: {Path(OUTPUT_DIR) / 'scaler.pkl'}")
556
+ logger.info(f" - Predictions: {results_csv}")
557
+ logger.info(f" - Detailed results: {Path(OUTPUT_DIR) / 'test_results_detailed.json'}")
558
+ logger.info(f" - Training log: {Path(OUTPUT_DIR) / 'training.log'}")
559
+ logger.info(f" - Plots: {img_dir}")
52 Indobert-base-p1_with_law_with_xgboost.py CHANGED
@@ -27,6 +27,29 @@ from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
27
 
28
  # Import XGBoost
29
  import xgboost as xgb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  # ======================================================
32
  # User Configuration
@@ -48,9 +71,15 @@ def set_seed(seed: int):
48
 
49
  set_seed(SEED)
50
 
 
 
 
51
  HF_TOKEN = os.environ.get('HF_TOKEN') # Set HF_TOKEN environment variable
52
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
53
- print(f"Device detected: {device}")
 
 
 
54
 
55
  # ======================================================
56
  # 1. Dataset Download & Prep
@@ -58,7 +87,7 @@ print(f"Device detected: {device}")
58
  REPO_ID = "evanslur/skripsi"
59
  ZIP_FILENAME = "dataset.zip"
60
 
61
- print("Downloading dataset...")
62
  zip_path = hf_hub_download(repo_id=REPO_ID, filename=ZIP_FILENAME, repo_type="dataset", token=HF_TOKEN)
63
 
64
  extract_dir = Path("./colloquial_data")
@@ -111,15 +140,17 @@ def preprocess_text(text):
111
  t = re.sub(r"\s+", ' ', t).strip().lower()
112
  return t
113
 
114
- print('Preprocessing text...')
115
  for split in loaded:
116
  loaded[split] = loaded[split].map(lambda x: {'text': preprocess_text(x['text'])}, num_proc=4)
117
 
 
 
118
  # ======================================================
119
  # 3. Label Scaling
120
  # ======================================================
121
  # Meskipun Tree-Based model tidak wajib scaling, ini membantu normalisasi loss function
122
- print("Fitting StandardScaler...")
123
  scaler = StandardScaler()
124
  train_labels_raw = np.array(loaded['train']['day_sentence']).reshape(-1, 1)
125
  scaler.fit(train_labels_raw)
@@ -128,14 +159,17 @@ Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
128
  with open(Path(OUTPUT_DIR) / 'scaler.pkl', 'wb') as f:
129
  pickle.dump(scaler, f)
130
 
 
 
131
  # ======================================================
132
  # 4. Feature Extraction (IndoBERT)
133
  # ======================================================
134
- print(f"Loading IndoBERT: {MODEL_NAME}")
135
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
136
  encoder = AutoModel.from_pretrained(MODEL_NAME, token=HF_TOKEN)
137
  encoder.to(device)
138
  encoder.eval()
 
139
 
140
  def extract_embeddings(dataset_split, batch_size=32):
141
  all_embeddings = []
@@ -145,7 +179,7 @@ def extract_embeddings(dataset_split, batch_size=32):
145
  # Normalize labels
146
  labels_norm = scaler.transform(np.array(labels).reshape(-1, 1)).flatten()
147
 
148
- print(f"Extracting features for {len(texts)} samples...")
149
  for i in tqdm(range(0, len(texts), batch_size)):
150
  batch_texts = texts[i : i + batch_size]
151
  inputs = tokenizer(batch_texts, padding=True, truncation=True, max_length=MAX_LENGTH, return_tensors="pt").to(device)
@@ -164,11 +198,26 @@ X_test, y_test = extract_embeddings(loaded['test'], BATCH_SIZE)
164
  # ======================================================
165
  # 5. Train XGBoost (Tree Based Model)
166
  # ======================================================
167
- print("\n" + "="*50)
168
- print("🌳 Training XGBoost Regressor...")
169
- print("="*50)
 
 
170
 
171
  # Konfigurasi XGBoost
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  xgb_model = xgb.XGBRegressor(
173
  n_estimators=1000, # Jumlah pohon
174
  learning_rate=0.05, # Kecepatan belajar (makin kecil makin teliti tapi lambat)
@@ -188,10 +237,17 @@ xgb_model.fit(
188
  verbose=100
189
  )
190
 
191
- print("✅ XGBoost Training Completed!")
 
 
 
 
 
 
192
  xgb_model.save_model(Path(OUTPUT_DIR) / "xgboost_model.json")
193
  encoder.save_pretrained(Path(OUTPUT_DIR) / "encoder")
194
  tokenizer.save_pretrained(OUTPUT_DIR)
 
195
 
196
  # ======================================================
197
  # 6. Evaluation
@@ -207,13 +263,37 @@ def evaluate_model(model, X, y_true_norm, scaler, prefix="Test"):
207
  mae = mean_absolute_error(y_true_denorm, preds_denorm)
208
  r2 = r2_score(y_true_denorm, preds_denorm)
209
 
210
- print(f"\n📊 {prefix} Results:")
211
- print(f" RMSE: {rmse:.2f} days")
212
- print(f" MAE: {mae:.2f} days")
213
- print(f" R2: {r2:.4f}")
214
- return preds_denorm, y_true_denorm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
- test_preds, test_true = evaluate_model(xgb_model, X_test, y_test, scaler, prefix="Test")
 
 
 
 
 
 
 
217
 
218
  # ======================================================
219
  # 7. Save Results & Plot
@@ -227,24 +307,152 @@ results_df = pd.DataFrame({
227
 
228
  results_csv = Path(OUTPUT_DIR) / 'xgboost_test_predictions.csv'
229
  results_df.to_csv(results_csv, index=False)
230
- print(f"\n💾 Results saved to {results_csv}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
- # Plot
233
  img_dir = Path(OUTPUT_DIR) / 'plots'
234
  img_dir.mkdir(parents=True, exist_ok=True)
235
- plt.figure(figsize=(6, 6))
236
- plt.scatter(results_df['true_label'], results_df['prediction'], alpha=0.5, color='green')
 
 
237
  lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
238
- plt.plot(lims, lims, '--', color='gray')
239
- plt.title(f'XGBoost: True vs Predicted')
240
- plt.xlabel('True Days')
241
- plt.ylabel('Predicted Days')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  plt.tight_layout()
243
- plt.savefig(img_dir / 'xgboost_scatter.png')
244
- print(f"🖼️ Plot saved to {img_dir}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  # ======================================================
247
- # 8. Inference Function
248
  # ======================================================
249
  def predict_sentence_tree(text):
250
  clean_text = preprocess_text(text)
@@ -258,4 +466,94 @@ def predict_sentence_tree(text):
258
  pred_days = scaler.inverse_transform(pred_norm.reshape(-1, 1))[0][0]
259
  return max(0, pred_days)
260
 
261
- print("\n🔮 Inference ready: predict_sentence_tree('text')")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  # Import XGBoost
29
  import xgboost as xgb
30
+ import logging
31
+ from sklearn.metrics import mean_absolute_percentage_error
32
+
33
+ # ======================================================
34
+ # Logging Setup
35
+ # ======================================================
36
+ def setup_logging(output_dir):
37
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
38
+ log_file = Path(output_dir) / 'training.log'
39
+
40
+ # Remove existing handlers
41
+ for handler in logging.root.handlers[:]:
42
+ logging.root.removeHandler(handler)
43
+
44
+ logging.basicConfig(
45
+ level=logging.INFO,
46
+ format='%(asctime)s - %(levelname)s - %(message)s',
47
+ handlers=[
48
+ logging.FileHandler(log_file, mode='w', encoding='utf-8'),
49
+ logging.StreamHandler()
50
+ ]
51
+ )
52
+ return logging.getLogger(__name__)
53
 
54
  # ======================================================
55
  # User Configuration
 
71
 
72
  set_seed(SEED)
73
 
74
+ # Setup logging
75
+ logger = setup_logging(OUTPUT_DIR)
76
+
77
  HF_TOKEN = os.environ.get('HF_TOKEN') # Set HF_TOKEN environment variable
78
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
79
+ logger.info(f"Device detected: {device}")
80
+ logger.info(f"Model: {MODEL_NAME}")
81
+ logger.info(f"Output directory: {OUTPUT_DIR}")
82
+ logger.info(f"Max length: {MAX_LENGTH}, Batch size: {BATCH_SIZE}, Seed: {SEED}")
83
 
84
  # ======================================================
85
  # 1. Dataset Download & Prep
 
87
  REPO_ID = "evanslur/skripsi"
88
  ZIP_FILENAME = "dataset.zip"
89
 
90
+ logger.info("Downloading dataset...")
91
  zip_path = hf_hub_download(repo_id=REPO_ID, filename=ZIP_FILENAME, repo_type="dataset", token=HF_TOKEN)
92
 
93
  extract_dir = Path("./colloquial_data")
 
140
  t = re.sub(r"\s+", ' ', t).strip().lower()
141
  return t
142
 
143
+ logger.info('Preprocessing text...')
144
  for split in loaded:
145
  loaded[split] = loaded[split].map(lambda x: {'text': preprocess_text(x['text'])}, num_proc=4)
146
 
147
+ logger.info(f"Dataset loaded - Train: {len(loaded['train'])}, Val: {len(loaded['validation'])}, Test: {len(loaded['test'])}")
148
+
149
  # ======================================================
150
  # 3. Label Scaling
151
  # ======================================================
152
  # Meskipun Tree-Based model tidak wajib scaling, ini membantu normalisasi loss function
153
+ logger.info("Fitting StandardScaler...")
154
  scaler = StandardScaler()
155
  train_labels_raw = np.array(loaded['train']['day_sentence']).reshape(-1, 1)
156
  scaler.fit(train_labels_raw)
 
159
  with open(Path(OUTPUT_DIR) / 'scaler.pkl', 'wb') as f:
160
  pickle.dump(scaler, f)
161
 
162
+ logger.info(f"Scaler fitted: mean={scaler.mean_[0]:.2f}, std={scaler.scale_[0]:.2f}")
163
+
164
  # ======================================================
165
  # 4. Feature Extraction (IndoBERT)
166
  # ======================================================
167
+ logger.info(f"Loading IndoBERT: {MODEL_NAME}")
168
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
169
  encoder = AutoModel.from_pretrained(MODEL_NAME, token=HF_TOKEN)
170
  encoder.to(device)
171
  encoder.eval()
172
+ logger.info("IndoBERT encoder loaded successfully")
173
 
174
  def extract_embeddings(dataset_split, batch_size=32):
175
  all_embeddings = []
 
179
  # Normalize labels
180
  labels_norm = scaler.transform(np.array(labels).reshape(-1, 1)).flatten()
181
 
182
+ logger.info(f"Extracting features for {len(texts)} samples...")
183
  for i in tqdm(range(0, len(texts), batch_size)):
184
  batch_texts = texts[i : i + batch_size]
185
  inputs = tokenizer(batch_texts, padding=True, truncation=True, max_length=MAX_LENGTH, return_tensors="pt").to(device)
 
198
  # ======================================================
199
  # 5. Train XGBoost (Tree Based Model)
200
  # ======================================================
201
+ logger.info("\n" + "="*50)
202
+ logger.info("🌳 Training XGBoost Regressor...")
203
+ logger.info("="*50)
204
+ logger.info(f"Feature dimension: {X_train.shape[1]}")
205
+ logger.info(f"Training samples: {X_train.shape[0]}, Validation samples: {X_val.shape[0]}, Test samples: {X_test.shape[0]}")
206
 
207
  # Konfigurasi XGBoost
208
+ xgb_params = {
209
+ 'n_estimators': 1000,
210
+ 'learning_rate': 0.05,
211
+ 'max_depth': 6,
212
+ 'subsample': 0.8,
213
+ 'colsample_bytree': 0.8,
214
+ 'objective': 'reg:squarederror',
215
+ 'n_jobs': -1,
216
+ 'random_state': SEED,
217
+ 'early_stopping_rounds': 50
218
+ }
219
+ logger.info(f"XGBoost parameters: {xgb_params}")
220
+
221
  xgb_model = xgb.XGBRegressor(
222
  n_estimators=1000, # Jumlah pohon
223
  learning_rate=0.05, # Kecepatan belajar (makin kecil makin teliti tapi lambat)
 
237
  verbose=100
238
  )
239
 
240
+ logger.info("✅ XGBoost Training Completed!")
241
+ logger.info(f"Best iteration: {xgb_model.best_iteration}")
242
+ logger.info(f"Best score: {xgb_model.best_score:.6f}")
243
+
244
+ # Get training history
245
+ evals_result = xgb_model.evals_result()
246
+
247
  xgb_model.save_model(Path(OUTPUT_DIR) / "xgboost_model.json")
248
  encoder.save_pretrained(Path(OUTPUT_DIR) / "encoder")
249
  tokenizer.save_pretrained(OUTPUT_DIR)
250
+ logger.info(f"Model saved to {OUTPUT_DIR}")
251
 
252
  # ======================================================
253
  # 6. Evaluation
 
263
  mae = mean_absolute_error(y_true_denorm, preds_denorm)
264
  r2 = r2_score(y_true_denorm, preds_denorm)
265
 
266
+ # Additional metrics
267
+ median_ae = np.median(np.abs(y_true_denorm - preds_denorm))
268
+ max_error = np.max(np.abs(y_true_denorm - preds_denorm))
269
+
270
+ # MAPE (avoid division by zero)
271
+ mask = y_true_denorm != 0
272
+ if mask.sum() > 0:
273
+ mape = mean_absolute_percentage_error(y_true_denorm[mask], preds_denorm[mask]) * 100
274
+ else:
275
+ mape = np.nan
276
+
277
+ logger.info(f"\n📊 {prefix} Results:")
278
+ logger.info(f" MSE: {mse:.2f} days²")
279
+ logger.info(f" RMSE: {rmse:.2f} days")
280
+ logger.info(f" MAE: {mae:.2f} days")
281
+ logger.info(f" Median AE: {median_ae:.2f} days")
282
+ logger.info(f" Max Error: {max_error:.2f} days")
283
+ logger.info(f" R2: {r2:.4f}")
284
+ if not np.isnan(mape):
285
+ logger.info(f" MAPE: {mape:.2f}%")
286
+
287
+ return preds_denorm, y_true_denorm, {'mse': mse, 'rmse': rmse, 'mae': mae, 'median_ae': median_ae, 'max_error': max_error, 'r2': r2, 'mape': mape}
288
 
289
+ # Evaluate all splits
290
+ logger.info("\n" + "="*50)
291
+ logger.info("📊 Evaluating on all splits...")
292
+ logger.info("="*50)
293
+
294
+ train_preds, train_true, train_metrics = evaluate_model(xgb_model, X_train, y_train, scaler, prefix="Train")
295
+ val_preds, val_true, val_metrics = evaluate_model(xgb_model, X_val, y_val, scaler, prefix="Validation")
296
+ test_preds, test_true, test_metrics = evaluate_model(xgb_model, X_test, y_test, scaler, prefix="Test")
297
 
298
  # ======================================================
299
  # 7. Save Results & Plot
 
307
 
308
  results_csv = Path(OUTPUT_DIR) / 'xgboost_test_predictions.csv'
309
  results_df.to_csv(results_csv, index=False)
310
+ logger.info(f"\n💾 Results saved to {results_csv}")
311
+
312
+ # Save detailed results JSON
313
+ detailed_results = {
314
+ 'model': 'XGBoost',
315
+ 'encoder': MODEL_NAME,
316
+ 'dataset': 'colloquial_with_law',
317
+ 'xgb_params': xgb_params,
318
+ 'best_iteration': int(xgb_model.best_iteration),
319
+ 'best_score': float(xgb_model.best_score),
320
+ 'train_metrics': {k: float(v) if not np.isnan(v) else None for k, v in train_metrics.items()},
321
+ 'val_metrics': {k: float(v) if not np.isnan(v) else None for k, v in val_metrics.items()},
322
+ 'test_metrics': {k: float(v) if not np.isnan(v) else None for k, v in test_metrics.items()},
323
+ 'prediction_stats': {
324
+ 'mean': float(np.mean(test_preds)),
325
+ 'std': float(np.std(test_preds)),
326
+ 'min': float(np.min(test_preds)),
327
+ 'max': float(np.max(test_preds))
328
+ },
329
+ 'true_label_stats': {
330
+ 'mean': float(np.mean(test_true)),
331
+ 'std': float(np.std(test_true)),
332
+ 'min': float(np.min(test_true)),
333
+ 'max': float(np.max(test_true))
334
+ },
335
+ 'error_percentiles': {
336
+ f'p{p}': float(np.percentile(results_df['error'], p)) for p in [10, 25, 50, 75, 90, 95, 99]
337
+ },
338
+ 'accuracy_within_ranges': {
339
+ f'within_{threshold}': float(np.sum(results_df['error'] <= threshold) / len(results_df) * 100)
340
+ for threshold in [100, 250, 500, 750, 1000]
341
+ }
342
+ }
343
+
344
+ with open(Path(OUTPUT_DIR) / 'test_results_detailed.json', 'w') as f:
345
+ json.dump(detailed_results, f, indent=2)
346
+ logger.info(f"Detailed results saved to {Path(OUTPUT_DIR) / 'test_results_detailed.json'}")
347
+
348
+ # ======================================================
349
+ # 8. Plots
350
+ # ======================================================
351
+ logger.info("\n" + "="*50)
352
+ logger.info("🖼️ Generating plots...")
353
+ logger.info("="*50)
354
 
 
355
  img_dir = Path(OUTPUT_DIR) / 'plots'
356
  img_dir.mkdir(parents=True, exist_ok=True)
357
+
358
+ # Plot 1: Scatter plot - True vs Predicted
359
+ plt.figure(figsize=(8, 8))
360
+ plt.scatter(results_df['true_label'], results_df['prediction'], alpha=0.5, color='green', edgecolors='none', s=30)
361
  lims = [0, max(results_df['true_label'].max(), results_df['prediction'].max()) * 1.05]
362
+ plt.plot(lims, lims, '--', color='red', linewidth=2, label='Perfect Prediction')
363
+ plt.title(f'XGBoost: True vs Predicted\nRMSE={test_metrics["rmse"]:.2f}, MAE={test_metrics["mae"]:.2f}, R²={test_metrics["r2"]:.4f}', fontsize=12)
364
+ plt.xlabel('True Days', fontsize=11)
365
+ plt.ylabel('Predicted Days', fontsize=11)
366
+ plt.legend()
367
+ plt.grid(True, alpha=0.3)
368
+ plt.tight_layout()
369
+ plt.savefig(img_dir / 'scatter_true_vs_predicted.png', dpi=150)
370
+ plt.close()
371
+ logger.info(f" Saved: scatter_true_vs_predicted.png")
372
+
373
+ # Plot 2: Residual Plot
374
+ plt.figure(figsize=(10, 6))
375
+ residuals = test_preds - test_true
376
+ plt.scatter(test_true, residuals, alpha=0.5, color='blue', edgecolors='none', s=30)
377
+ plt.axhline(y=0, color='red', linestyle='--', linewidth=2)
378
+ plt.title('Residual Plot: Predicted - True', fontsize=12)
379
+ plt.xlabel('True Days', fontsize=11)
380
+ plt.ylabel('Residual (Predicted - True)', fontsize=11)
381
+ plt.grid(True, alpha=0.3)
382
+ plt.tight_layout()
383
+ plt.savefig(img_dir / 'residual_plot.png', dpi=150)
384
+ plt.close()
385
+ logger.info(f" Saved: residual_plot.png")
386
+
387
+ # Plot 3: Error Distribution Histogram
388
+ plt.figure(figsize=(10, 6))
389
+ plt.hist(results_df['error'], bins=50, color='steelblue', edgecolor='white', alpha=0.8)
390
+ plt.axvline(x=test_metrics['mae'], color='red', linestyle='--', linewidth=2, label=f'MAE = {test_metrics["mae"]:.2f}')
391
+ plt.axvline(x=test_metrics['median_ae'], color='orange', linestyle='--', linewidth=2, label=f'Median AE = {test_metrics["median_ae"]:.2f}')
392
+ plt.title('Distribution of Absolute Errors', fontsize=12)
393
+ plt.xlabel('Absolute Error (Days)', fontsize=11)
394
+ plt.ylabel('Frequency', fontsize=11)
395
+ plt.legend()
396
+ plt.grid(True, alpha=0.3)
397
+ plt.tight_layout()
398
+ plt.savefig(img_dir / 'error_distribution.png', dpi=150)
399
+ plt.close()
400
+ logger.info(f" Saved: error_distribution.png")
401
+
402
+ # Plot 4: Training Curve (XGBoost Loss)
403
+ if evals_result:
404
+ plt.figure(figsize=(10, 6))
405
+ train_rmse = evals_result['validation_0']['rmse']
406
+ val_rmse = evals_result['validation_1']['rmse']
407
+ epochs = range(1, len(train_rmse) + 1)
408
+ plt.plot(epochs, train_rmse, 'b-', label='Train RMSE', linewidth=2)
409
+ plt.plot(epochs, val_rmse, 'r-', label='Validation RMSE', linewidth=2)
410
+ plt.axvline(x=xgb_model.best_iteration, color='green', linestyle='--', linewidth=1.5, label=f'Best iteration: {xgb_model.best_iteration}')
411
+ plt.title('XGBoost Training Curve', fontsize=12)
412
+ plt.xlabel('Boosting Round', fontsize=11)
413
+ plt.ylabel('RMSE (Normalized)', fontsize=11)
414
+ plt.legend()
415
+ plt.grid(True, alpha=0.3)
416
+ plt.tight_layout()
417
+ plt.savefig(img_dir / 'training_curve.png', dpi=150)
418
+ plt.close()
419
+ logger.info(f" Saved: training_curve.png")
420
+
421
+ # Plot 5: Box plot of errors by label range
422
+ plt.figure(figsize=(12, 6))
423
+ bins = [0, 365, 730, 1460, 2920, float('inf')] # 0-1yr, 1-2yr, 2-4yr, 4-8yr, 8yr+
424
+ labels_cat = ['0-1 year', '1-2 years', '2-4 years', '4-8 years', '8+ years']
425
+ results_df['label_category'] = pd.cut(results_df['true_label'], bins=bins, labels=labels_cat)
426
+ sns.boxplot(x='label_category', y='error', data=results_df, palette='viridis')
427
+ plt.title('Error Distribution by Sentence Length Category', fontsize=12)
428
+ plt.xlabel('True Sentence Category', fontsize=11)
429
+ plt.ylabel('Absolute Error (Days)', fontsize=11)
430
+ plt.xticks(rotation=15)
431
+ plt.grid(True, alpha=0.3, axis='y')
432
  plt.tight_layout()
433
+ plt.savefig(img_dir / 'error_by_category_boxplot.png', dpi=150)
434
+ plt.close()
435
+ logger.info(f" Saved: error_by_category_boxplot.png")
436
+
437
+ # Plot 6: Feature Importance (Top 20)
438
+ plt.figure(figsize=(10, 8))
439
+ importances = xgb_model.feature_importances_
440
+ top_k = 20
441
+ top_indices = np.argsort(importances)[-top_k:][::-1]
442
+ plt.barh(range(top_k), importances[top_indices], color='teal')
443
+ plt.yticks(range(top_k), [f'Feature {i}' for i in top_indices])
444
+ plt.xlabel('Importance', fontsize=11)
445
+ plt.title(f'Top {top_k} Feature Importances (XGBoost)', fontsize=12)
446
+ plt.gca().invert_yaxis()
447
+ plt.tight_layout()
448
+ plt.savefig(img_dir / 'feature_importance.png', dpi=150)
449
+ plt.close()
450
+ logger.info(f" Saved: feature_importance.png")
451
+
452
+ logger.info(f"🖼️ All plots saved to {img_dir}")
453
 
454
  # ======================================================
455
+ # 9. Inference Function
456
  # ======================================================
457
  def predict_sentence_tree(text):
458
  clean_text = preprocess_text(text)
 
466
  pred_days = scaler.inverse_transform(pred_norm.reshape(-1, 1))[0][0]
467
  return max(0, pred_days)
468
 
469
+ logger.info("\n🔮 Inference ready: predict_sentence_tree('text')")
470
+
471
+ # ======================================================
472
+ # 10. Final Summary
473
+ # ======================================================
474
+ logger.info("\n" + "="*70)
475
+ logger.info("📈 TEST SET METRICS (Original Scale - Days)")
476
+ logger.info("="*70)
477
+
478
+ # Extract metrics
479
+ mse = test_metrics['mse']
480
+ rmse = test_metrics['rmse']
481
+ mae = test_metrics['mae']
482
+ median_ae = test_metrics['median_ae']
483
+ max_error = test_metrics['max_error']
484
+ r2 = test_metrics['r2']
485
+ mape = test_metrics.get('mape', np.nan)
486
+ min_error = np.min(results_df['error'])
487
+
488
+ # Statistics
489
+ pred_mean = np.mean(test_preds)
490
+ pred_std = np.std(test_preds)
491
+ pred_min = np.min(test_preds)
492
+ pred_max = np.max(test_preds)
493
+
494
+ true_mean = np.mean(test_true)
495
+ true_std = np.std(test_true)
496
+ true_min = np.min(test_true)
497
+ true_max = np.max(test_true)
498
+
499
+ logger.info("\n🎯 ERROR METRICS:")
500
+ logger.info(f" MSE: {mse:>12,.2f} days²")
501
+ logger.info(f" RMSE: {rmse:>12,.2f} days")
502
+ logger.info(f" MAE: {mae:>12,.2f} days")
503
+ logger.info(f" Median AE: {median_ae:>12,.2f} days")
504
+ logger.info(f" Max Error: {max_error:>12,.2f} days")
505
+ logger.info(f" Min Error: {min_error:>12,.2f} days")
506
+ if not np.isnan(mape):
507
+ logger.info(f" MAPE: {mape:>12,.2f} %")
508
+ logger.info(f" R² Score: {r2:>12,.4f}")
509
+
510
+ logger.info("\n📊 PREDICTION STATISTICS:")
511
+ logger.info(f" Mean: {pred_mean:>12,.2f} days")
512
+ logger.info(f" Std Dev: {pred_std:>12,.2f} days")
513
+ logger.info(f" Min: {pred_min:>12,.2f} days")
514
+ logger.info(f" Max: {pred_max:>12,.2f} days")
515
+
516
+ logger.info("\n📊 TRUE LABEL STATISTICS:")
517
+ logger.info(f" Mean: {true_mean:>12,.2f} days")
518
+ logger.info(f" Std Dev: {true_std:>12,.2f} days")
519
+ logger.info(f" Min: {true_min:>12,.2f} days")
520
+ logger.info(f" Max: {true_max:>12,.2f} days")
521
+
522
+ # Error distribution analysis
523
+ logger.info("\n📉 ERROR DISTRIBUTION:")
524
+ percentiles = [10, 25, 50, 75, 90, 95, 99]
525
+ logger.info(" Percentiles of Absolute Error:")
526
+ for p in percentiles:
527
+ perc_val = np.percentile(results_df['error'], p)
528
+ logger.info(f" {p}th percentile: {perc_val:>12,.2f} days")
529
+
530
+ # Accuracy within ranges
531
+ logger.info("\n🎯 ACCURACY WITHIN ERROR RANGES:")
532
+ for threshold in [100, 250, 500, 750, 1000]:
533
+ acc = np.sum(results_df['error'] <= threshold) / len(results_df) * 100
534
+ logger.info(f" Within {threshold:>4} days: {acc:>12.2f}%")
535
+
536
+ # Sample predictions
537
+ logger.info("\n" + "="*70)
538
+ logger.info("🧪 SAMPLE PREDICTIONS (First 10)")
539
+ logger.info("="*70)
540
+ for i in range(min(10, len(results_df))):
541
+ row = results_df.iloc[i]
542
+ logger.info(f"Sample {i+1}:")
543
+ logger.info(f" File: {row['file_name']}")
544
+ logger.info(f" True: {row['true_label']:.2f} days")
545
+ logger.info(f" Pred: {row['prediction']:.2f} days")
546
+ logger.info(f" Diff: {row['error']:.2f} days")
547
+ logger.info("-" * 30)
548
+
549
+ logger.info("\n" + "="*70)
550
+ logger.info("✅ TRAINING AND EVALUATION COMPLETE!")
551
+ logger.info("="*70)
552
+ logger.info(f"\nOutput files:")
553
+ logger.info(f" - Model: {Path(OUTPUT_DIR) / 'xgboost_model.json'}")
554
+ logger.info(f" - Encoder: {Path(OUTPUT_DIR) / 'encoder'}")
555
+ logger.info(f" - Scaler: {Path(OUTPUT_DIR) / 'scaler.pkl'}")
556
+ logger.info(f" - Predictions: {results_csv}")
557
+ logger.info(f" - Detailed results: {Path(OUTPUT_DIR) / 'test_results_detailed.json'}")
558
+ logger.info(f" - Training log: {Path(OUTPUT_DIR) / 'training.log'}")
559
+ logger.info(f" - Plots: {img_dir}")
requirements.txt CHANGED
@@ -12,6 +12,7 @@ pyarrow>=21.0.0,<25.0.0
12
  matplotlib
13
  seaborn
14
  xgboost
 
15
 
16
  # NOTE: We intentionally do NOT pin `torch` here. Install `torch` separately
17
  # using the official PyTorch instructions for your CUDA / CPU setup:
 
12
  matplotlib
13
  seaborn
14
  xgboost
15
+ sys
16
 
17
  # NOTE: We intentionally do NOT pin `torch` here. Install `torch` separately
18
  # using the official PyTorch instructions for your CUDA / CPU setup:
run_experiments.py CHANGED
@@ -5,6 +5,7 @@ Modify the 'scripts' list to include the files you want to run.
5
 
6
  import subprocess
7
  import sys
 
8
  import time
9
  from datetime import datetime
10
 
@@ -56,6 +57,14 @@ def main():
56
 
57
  for i, script in enumerate(scripts, 1):
58
  print(f"\n[{i}/{len(scripts)}]", end="")
 
 
 
 
 
 
 
 
59
  success, elapsed = run_script(script)
60
  results.append((script, success, elapsed))
61
 
 
5
 
6
  import subprocess
7
  import sys
8
+ import os
9
  import time
10
  from datetime import datetime
11
 
 
57
 
58
  for i, script in enumerate(scripts, 1):
59
  print(f"\n[{i}/{len(scripts)}]", end="")
60
+
61
+ # Check if output directory exists
62
+ output_dir = script.replace('.py', '')
63
+ if os.path.exists(output_dir):
64
+ print(f" Skipping {script} (Output directory '{output_dir}' already exists)")
65
+ results.append((script, True, 0))
66
+ continue
67
+
68
  success, elapsed = run_script(script)
69
  results.append((script, success, elapsed))
70