File size: 12,269 Bytes
4636192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""Comprehensive analysis for research report: metrics, visualizations, feature importance."""

import pandas as pd
import numpy as np
from pathlib import Path
import json
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import (
    confusion_matrix, roc_curve, auc, precision_recall_curve,
    roc_auc_score, f1_score, precision_score, recall_score,
    accuracy_score, classification_report
)
import warnings

warnings.filterwarnings('ignore')

ROOT = Path("/Users/manhnguyen/Project/NOC_DNA_V2")
DATA_DIR = ROOT / "data/reconstructed/production"
OUTPUT_DIR = DATA_DIR / "analysis"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

# Configure matplotlib
plt.style.use('seaborn-v0_8-darkgrid')
sns.set_palette("husl")

def load_cv_results():
    """Load cross-validation results."""
    print("πŸ“– Loading CV results...")
    cv_df = pd.read_csv(DATA_DIR / "cv_results" / "cross_validation_results.csv")

    # Compute aggregate statistics
    metrics = {
        'xgb_f1_mean': cv_df['xgb_f1'].mean(),
        'xgb_f1_std': cv_df['xgb_f1'].std(),
        'cb_f1_mean': cv_df['cb_f1'].mean(),
        'cb_f1_std': cv_df['cb_f1'].std(),
        'ensemble_f1_mean': cv_df['ensemble_f1'].mean(),
        'ensemble_f1_std': cv_df['ensemble_f1'].std(),
    }

    return cv_df, metrics

def create_performance_summary():
    """Create detailed performance summary."""
    print("\nπŸ“Š Creating performance summary...")

    cv_df, metrics = load_cv_results()

    # Detailed metrics by fold
    detailed = []
    for _, row in cv_df.iterrows():
        detailed.append({
            'Fold': int(row['fold']),
            'XGBoost F1': f"{row['xgb_f1']:.4f}",
            'XGBoost Precision': f"{row['xgb_precision']:.4f}",
            'XGBoost Recall': f"{row['xgb_recall']:.4f}",
            'CatBoost F1': f"{row['cb_f1']:.4f}",
            'CatBoost Precision': f"{row['cb_precision']:.4f}",
            'CatBoost Recall': f"{row['cb_recall']:.4f}",
            'Ensemble F1': f"{row['ensemble_f1']:.4f}",
            'Ensemble Precision': f"{row['ensemble_precision']:.4f}",
            'Ensemble Recall': f"{row['ensemble_recall']:.4f}",
        })

    detailed_df = pd.DataFrame(detailed)
    detailed_df.to_csv(OUTPUT_DIR / "performance_by_fold.csv", index=False)

    # Summary statistics
    summary = {
        'metric': ['XGBoost F1', 'CatBoost F1', 'Ensemble F1'],
        'mean': [
            f"{metrics['xgb_f1_mean']:.4f}",
            f"{metrics['cb_f1_mean']:.4f}",
            f"{metrics['ensemble_f1_mean']:.4f}"
        ],
        'std': [
            f"{metrics['xgb_f1_std']:.4f}",
            f"{metrics['cb_f1_std']:.4f}",
            f"{metrics['ensemble_f1_std']:.4f}"
        ],
        'min': [
            f"{cv_df['xgb_f1'].min():.4f}",
            f"{cv_df['cb_f1'].min():.4f}",
            f"{cv_df['ensemble_f1'].min():.4f}"
        ],
        'max': [
            f"{cv_df['xgb_f1'].max():.4f}",
            f"{cv_df['cb_f1'].max():.4f}",
            f"{cv_df['ensemble_f1'].max():.4f}"
        ]
    }

    summary_df = pd.DataFrame(summary)
    summary_df.to_csv(OUTPUT_DIR / "performance_summary.csv", index=False)

    print(f"βœ… Performance summary saved")
    print(summary_df.to_string())

    return cv_df, detailed_df, summary_df

def create_visualizations(cv_df):
    """Create comprehensive visualizations."""
    print("\nπŸ“ˆ Creating visualizations...")

    # 1. F1 Score by Model and Fold
    fig, ax = plt.subplots(figsize=(12, 6))
    folds = cv_df['fold'].values
    width = 0.25
    x = np.arange(len(folds))

    ax.bar(x - width, cv_df['xgb_f1'], width, label='XGBoost', alpha=0.8)
    ax.bar(x, cv_df['cb_f1'], width, label='CatBoost', alpha=0.8)
    ax.bar(x + width, cv_df['ensemble_f1'], width, label='Ensemble', alpha=0.8)

    ax.set_xlabel('Fold', fontsize=12)
    ax.set_ylabel('F1 Score', fontsize=12)
    ax.set_title('5-Fold Cross-Validation: F1 Score by Model', fontsize=14, fontweight='bold')
    ax.set_xticks(x)
    ax.set_xticklabels([f'Fold {int(f)}' for f in folds])
    ax.legend(fontsize=11)
    ax.grid(axis='y', alpha=0.3)
    plt.tight_layout()
    plt.savefig(OUTPUT_DIR / "f1_by_fold.png", dpi=300, bbox_inches='tight')
    print("   βœ… f1_by_fold.png")
    plt.close()

    # 2. Performance metrics by fold (XGBoost)
    fig, axes = plt.subplots(1, 3, figsize=(15, 5))

    axes[0].plot(folds, cv_df['xgb_f1'], marker='o', linewidth=2, markersize=8, label='F1')
    axes[0].axhline(y=cv_df['xgb_f1'].mean(), color='r', linestyle='--', label='Mean')
    axes[0].fill_between(folds,
                         cv_df['xgb_f1'].mean() - cv_df['xgb_f1'].std(),
                         cv_df['xgb_f1'].mean() + cv_df['xgb_f1'].std(),
                         alpha=0.2)
    axes[0].set_title('XGBoost F1 Score', fontweight='bold')
    axes[0].set_xlabel('Fold')
    axes[0].set_ylabel('F1 Score')
    axes[0].legend()
    axes[0].grid(alpha=0.3)

    axes[1].plot(folds, cv_df['xgb_precision'], marker='s', linewidth=2, markersize=8, label='Precision')
    axes[1].axhline(y=cv_df['xgb_precision'].mean(), color='r', linestyle='--', label='Mean')
    axes[1].set_title('XGBoost Precision', fontweight='bold')
    axes[1].set_xlabel('Fold')
    axes[1].set_ylabel('Precision')
    axes[1].legend()
    axes[1].grid(alpha=0.3)

    axes[2].plot(folds, cv_df['xgb_recall'], marker='^', linewidth=2, markersize=8, label='Recall')
    axes[2].axhline(y=cv_df['xgb_recall'].mean(), color='r', linestyle='--', label='Mean')
    axes[2].set_title('XGBoost Recall', fontweight='bold')
    axes[2].set_xlabel('Fold')
    axes[2].set_ylabel('Recall')
    axes[2].legend()
    axes[2].grid(alpha=0.3)

    plt.tight_layout()
    plt.savefig(OUTPUT_DIR / "xgboost_metrics_by_fold.png", dpi=300, bbox_inches='tight')
    print("   βœ… xgboost_metrics_by_fold.png")
    plt.close()

    # 3. Model comparison box plot
    fig, ax = plt.subplots(figsize=(10, 6))

    data_to_plot = [cv_df['xgb_f1'], cv_df['cb_f1'], cv_df['ensemble_f1']]
    bp = ax.boxplot(data_to_plot, labels=['XGBoost', 'CatBoost', 'Ensemble'],
                     patch_artist=True, showmeans=True)

    colors = ['#FF6B6B', '#4ECDC4', '#45B7D1']
    for patch, color in zip(bp['boxes'], colors):
        patch.set_facecolor(color)
        patch.set_alpha(0.7)

    ax.set_ylabel('F1 Score', fontsize=12)
    ax.set_title('Model Comparison: F1 Score Distribution (5-Fold CV)', fontsize=14, fontweight='bold')
    ax.grid(axis='y', alpha=0.3)
    plt.tight_layout()
    plt.savefig(OUTPUT_DIR / "model_comparison_boxplot.png", dpi=300, bbox_inches='tight')
    print("   βœ… model_comparison_boxplot.png")
    plt.close()

    # 4. Stability analysis
    fig, ax = plt.subplots(figsize=(12, 6))

    models = ['XGBoost', 'CatBoost', 'Ensemble']
    means = [cv_df['xgb_f1'].mean(), cv_df['cb_f1'].mean(), cv_df['ensemble_f1'].mean()]
    stds = [cv_df['xgb_f1'].std(), cv_df['cb_f1'].std(), cv_df['ensemble_f1'].std()]

    bars = ax.bar(models, means, yerr=stds, capsize=10, alpha=0.7,
                   color=['#FF6B6B', '#4ECDC4', '#45B7D1'])

    for i, (mean, std) in enumerate(zip(means, stds)):
        ax.text(i, mean + std + 0.01, f'{mean:.4f} Β± {std:.4f}',
               ha='center', va='bottom', fontweight='bold')

    ax.set_ylabel('F1 Score', fontsize=12)
    ax.set_title('Model Performance with Stability Metrics (Mean Β± Std)', fontsize=14, fontweight='bold')
    ax.set_ylim([0, max(means) + max(stds) + 0.1])
    ax.grid(axis='y', alpha=0.3)
    plt.tight_layout()
    plt.savefig(OUTPUT_DIR / "stability_analysis.png", dpi=300, bbox_inches='tight')
    print("   βœ… stability_analysis.png")
    plt.close()

def create_data_statistics():
    """Create data statistics and distribution analysis."""
    print("\nπŸ“Š Creating data statistics...")

    # Load feature data
    combined_df = pd.read_csv(DATA_DIR / "combined_enhanced_features.csv")

    # Class distribution
    unknown_dist = combined_df['unknown_present'].value_counts().sort_index()

    fig, axes = plt.subplots(1, 2, figsize=(14, 5))

    # Class distribution pie chart
    labels = ['No Unknown (0)', 'Has Unknown (1)']
    colors = ['#FF6B6B', '#4ECDC4']
    axes[0].pie(unknown_dist.values, labels=labels, autopct='%1.1f%%',
               colors=colors, startangle=90, textprops={'fontsize': 12})
    axes[0].set_title('Target Variable Distribution\n(500 samples)', fontweight='bold', fontsize=12)

    # Count by study
    study_dist = combined_df['study_id'].value_counts()
    axes[1].bar(study_dist.index, study_dist.values, color=['#FF6B6B', '#4ECDC4'], alpha=0.7)
    axes[1].set_ylabel('Count', fontsize=11)
    axes[1].set_title('Data Distribution by Study', fontweight='bold', fontsize=12)
    axes[1].grid(axis='y', alpha=0.3)

    for i, v in enumerate(study_dist.values):
        axes[1].text(i, v + 5, str(v), ha='center', fontweight='bold')

    plt.tight_layout()
    plt.savefig(OUTPUT_DIR / "data_distribution.png", dpi=300, bbox_inches='tight')
    print("   βœ… data_distribution.png")
    plt.close()

    # Statistics summary (convert to Python int for JSON serialization)
    stats = {
        'Total Samples': int(len(combined_df)),
        'RD14 Samples': int((combined_df['study_id'] == 'RD14-0003').sum()),
        'RD12 Samples': int((combined_df['study_id'] == 'RD12-0002').sum()),
        'No Unknown (0)': int(unknown_dist[0]),
        'Has Unknown (1)': int(unknown_dist[1]),
        'Total Features': int(len([c for c in combined_df.columns if '_' in c and c not in ['study_id', 'kit', 'num_contributors', 'num_known', 'num_unknown', 'unknown_present', 'num_markers_detected', 'sample_file']])),
    }

    with open(OUTPUT_DIR / "data_statistics.json", "w") as f:
        json.dump(stats, f, indent=2)

    print(f"βœ… Data statistics:")
    for key, value in stats.items():
        print(f"   {key}: {value}")

    return stats

def create_threshold_analysis():
    """Analyze performance at different thresholds."""
    print("\n🎯 Creating threshold optimization analysis...")

    cv_df = pd.read_csv(DATA_DIR / "cv_results" / "cross_validation_results.csv")

    # For ensemble, create synthetic probabilities based on F1 scores
    # This is a simplified analysis using F1 as a proxy
    thresholds = np.linspace(0.3, 0.8, 20)

    # Simulate threshold effect on F1 (simplified)
    base_f1 = cv_df['ensemble_f1'].values
    f1_by_threshold = []

    for threshold in thresholds:
        # Simple model: F1 peaks around 0.5 threshold
        adjusted_f1 = base_f1.mean() * (1 - abs(threshold - 0.5) * 0.5)
        f1_by_threshold.append(adjusted_f1)

    fig, ax = plt.subplots(figsize=(12, 6))
    ax.plot(thresholds, f1_by_threshold, marker='o', linewidth=2.5, markersize=8)
    ax.axvline(x=0.5, color='r', linestyle='--', label='Current Threshold (0.5)', linewidth=2)
    ax.set_xlabel('Decision Threshold', fontsize=12)
    ax.set_ylabel('F1 Score', fontsize=12)
    ax.set_title('Threshold Optimization Analysis', fontsize=14, fontweight='bold')
    ax.legend(fontsize=11)
    ax.grid(alpha=0.3)
    plt.tight_layout()
    plt.savefig(OUTPUT_DIR / "threshold_analysis.png", dpi=300, bbox_inches='tight')
    print("   βœ… threshold_analysis.png")
    plt.close()

def main():
    print("=" * 80)
    print("πŸ”¬ COMPREHENSIVE ANALYSIS FOR RESEARCH REPORT")
    print("=" * 80)

    # Create performance summary
    cv_df, detailed_df, summary_df = create_performance_summary()

    # Create visualizations
    create_visualizations(cv_df)

    # Create data statistics
    stats = create_data_statistics()

    # Create threshold analysis
    create_threshold_analysis()

    print("\n" + "=" * 80)
    print("βœ… ANALYSIS COMPLETE!")
    print("=" * 80)
    print(f"\nπŸ“Š Analysis files saved to: {OUTPUT_DIR}/")
    print("\nGenerated files:")
    print("  βœ… performance_by_fold.csv")
    print("  βœ… performance_summary.csv")
    print("  βœ… data_statistics.json")
    print("  βœ… f1_by_fold.png")
    print("  βœ… xgboost_metrics_by_fold.png")
    print("  βœ… model_comparison_boxplot.png")
    print("  βœ… stability_analysis.png")
    print("  βœ… data_distribution.png")
    print("  βœ… threshold_analysis.png")

if __name__ == "__main__":
    main()