| """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) |
|
|
| |
| 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") |
|
|
| |
| 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 = [] |
| 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 = { |
| '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...") |
|
|
| |
| 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() |
|
|
| |
| 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() |
|
|
| |
| 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() |
|
|
| |
| 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...") |
|
|
| |
| combined_df = pd.read_csv(DATA_DIR / "combined_enhanced_features.csv") |
|
|
| |
| unknown_dist = combined_df['unknown_present'].value_counts().sort_index() |
|
|
| fig, axes = plt.subplots(1, 2, figsize=(14, 5)) |
|
|
| |
| 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) |
|
|
| |
| 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() |
|
|
| |
| 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") |
|
|
| |
| |
| thresholds = np.linspace(0.3, 0.8, 20) |
|
|
| |
| base_f1 = cv_df['ensemble_f1'].values |
| f1_by_threshold = [] |
|
|
| for threshold in thresholds: |
| |
| 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) |
|
|
| |
| cv_df, detailed_df, summary_df = create_performance_summary() |
|
|
| |
| create_visualizations(cv_df) |
|
|
| |
| stats = create_data_statistics() |
|
|
| |
| 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() |
|
|