Download my/compare_aux_experiments.py from JustinTX/shinka-backup: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/JustinTX/shinka-backup/resolve/main/my/compare_aux_experiments.py
- Command line
-
hf download hf://JustinTX/shinka-backup/my/compare_aux_experiments.py
-
curl -L -o compare_aux_experiments.py https://huggingface.co/JustinTX/shinka-backup/resolve/main/my/compare_aux_experiments.py
12.9 kB
| #!/usr/bin/env python3 | |
| """ | |
| Compare two auxiliary metrics experiments: | |
| 1. All Aux (7 metrics) | |
| 2. Refined Aux (4 positive-correlation metrics) | |
| """ | |
| import json | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| from pathlib import Path | |
| import glob | |
| # Experiment directories | |
| ALL_AUX_DIR = "examples/circle_packing/results/results_circle_packing_NO_vision_WITH_aux_20260118_072141" | |
| REFINED_AUX_DIR = "examples/circle_packing/results/results_circle_packing_NO_vision_WITH_refined_aux_20260118_205215" | |
| def load_generation_data(exp_dir): | |
| """Load data from all generation directories.""" | |
| gen_dirs = sorted(glob.glob(f"{exp_dir}/gen_*"), | |
| key=lambda x: int(x.split("gen_")[-1])) | |
| generations = [] | |
| for gen_dir in gen_dirs: | |
| gen_num = int(gen_dir.split("gen_")[-1]) | |
| # Try both possible structures | |
| metrics_path = None | |
| if Path(f"{gen_dir}/best/results/metrics.json").exists(): | |
| metrics_path = f"{gen_dir}/best/results/metrics.json" | |
| elif Path(f"{gen_dir}/results/metrics.json").exists(): | |
| metrics_path = f"{gen_dir}/results/metrics.json" | |
| if metrics_path: | |
| try: | |
| with open(metrics_path) as f: | |
| metrics = json.load(f) | |
| # Extract auxiliary metrics | |
| public_metrics = metrics.get('public_metrics', {}) | |
| aux_metrics = {} | |
| for key, value in public_metrics.items(): | |
| if key not in ['sum_radii', 'num_circles']: | |
| aux_metrics[key] = value | |
| generations.append({ | |
| 'generation': gen_num, | |
| 'score': metrics.get('combined_score', 0), | |
| 'correct': metrics.get('correct', False), | |
| 'metrics': metrics.get('public_metrics', {}), | |
| 'aux_metrics': aux_metrics, | |
| 'text_feedback': metrics.get('text_feedback', '') | |
| }) | |
| except Exception as e: | |
| print(f"Warning: Could not load {metrics_path}: {e}") | |
| return sorted(generations, key=lambda x: x['generation']) | |
| def compute_stats(data): | |
| """Compute statistics from generation data.""" | |
| if not data: | |
| return None | |
| gen_nums = [d['generation'] for d in data] | |
| scores = [d['score'] for d in data] | |
| # Compute best so far | |
| best_so_far = [] | |
| current_best = 0 | |
| for score in scores: | |
| current_best = max(current_best, score) | |
| best_so_far.append(current_best) | |
| return { | |
| 'generations': gen_nums, | |
| 'scores': scores, | |
| 'best_so_far': best_so_far, | |
| } | |
| def analyze_aux_metrics(data, name): | |
| """Analyze what auxiliary metrics are present.""" | |
| print(f"\n{'='*80}") | |
| print(f"π AUXILIARY METRICS ANALYSIS - {name}") | |
| print(f"{'='*80}") | |
| # Collect all unique metrics | |
| all_metrics = set() | |
| for prog in data: | |
| all_metrics.update(prog['aux_metrics'].keys()) | |
| if not all_metrics: | |
| print("β No auxiliary metrics found!") | |
| return | |
| print(f"\nβ Found {len(all_metrics)} auxiliary metrics:") | |
| for metric in sorted(all_metrics): | |
| print(f" β’ {metric}") | |
| # Check text feedback | |
| has_feedback = sum(1 for p in data if p.get('text_feedback')) | |
| print(f"\nπ Text Feedback:") | |
| print(f" β’ {has_feedback}/{len(data)} generations have text feedback") | |
| # Sample a few text feedbacks | |
| if has_feedback > 0: | |
| print(f"\nπ Sample Text Feedback (Gen 50):") | |
| for prog in data: | |
| if prog['generation'] == 50 and prog.get('text_feedback'): | |
| feedback = prog['text_feedback'] | |
| print(f" Length: {len(feedback)} chars") | |
| print(f" Preview:\n{feedback[:500]}") | |
| break | |
| # Analyze metric values over time | |
| print(f"\nπ Metric Values Evolution:") | |
| for metric in sorted(all_metrics): | |
| values = [] | |
| gens = [] | |
| for prog in data: | |
| if metric in prog['aux_metrics']: | |
| values.append(prog['aux_metrics'][metric]) | |
| gens.append(prog['generation']) | |
| if values: | |
| print(f"\n {metric}:") | |
| print(f" Initial (gen {gens[0]}): {values[0]:.4f}") | |
| if len(values) > 1: | |
| print(f" Final (gen {gens[-1]}): {values[-1]:.4f}") | |
| print(f" Min: {min(values):.4f}, Max: {max(values):.4f}, Mean: {np.mean(values):.4f}") | |
| def plot_comparison(all_aux_data, refined_aux_data, all_aux_stats, refined_stats): | |
| """Create detailed comparison plots.""" | |
| fig = plt.figure(figsize=(18, 12)) | |
| gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3) | |
| fig.suptitle('π¬ All Aux (7) vs Refined Aux (4) Comparison', | |
| fontsize=16, fontweight='bold') | |
| min_len = min(len(all_aux_stats['generations']), | |
| len(refined_stats['generations'])) | |
| all_gens = all_aux_stats['generations'][:min_len] | |
| refined_gens = refined_stats['generations'][:min_len] | |
| # Plot 1: Best Score Evolution (large) | |
| ax1 = fig.add_subplot(gs[0, :]) | |
| ax1.plot(all_gens, all_aux_stats['best_so_far'][:min_len], | |
| 'r-', linewidth=2.5, label='All Aux (7 metrics)', marker='o', markersize=3) | |
| ax1.plot(refined_gens, refined_stats['best_so_far'][:min_len], | |
| 'g-', linewidth=2.5, label='Refined Aux (4 metrics)', marker='^', markersize=3) | |
| ax1.set_xlabel('Generation', fontsize=12) | |
| ax1.set_ylabel('Best Score', fontsize=12) | |
| ax1.set_title('Best Score Evolution', fontsize=14, fontweight='bold') | |
| ax1.legend(fontsize=11) | |
| ax1.grid(True, alpha=0.3) | |
| # Add final scores | |
| all_final = all_aux_stats['best_so_far'][min_len-1] | |
| refined_final = refined_stats['best_so_far'][min_len-1] | |
| ax1.axhline(y=all_final, color='r', linestyle=':', alpha=0.3) | |
| ax1.axhline(y=refined_final, color='g', linestyle=':', alpha=0.3) | |
| ax1.text(0.02, 0.98, f'All Aux (7): {all_final:.4f}', | |
| transform=ax1.transAxes, verticalalignment='top', | |
| bbox=dict(boxstyle='round', facecolor='red', alpha=0.2), fontsize=11) | |
| ax1.text(0.02, 0.88, f'Refined (4): {refined_final:.4f}', | |
| transform=ax1.transAxes, verticalalignment='top', | |
| bbox=dict(boxstyle='round', facecolor='green', alpha=0.2), fontsize=11) | |
| # Plot 2: Delta from All Aux | |
| ax2 = fig.add_subplot(gs[1, 0]) | |
| delta = [(r - a) for r, a in zip( | |
| refined_stats['best_so_far'][:min_len], | |
| all_aux_stats['best_so_far'][:min_len] | |
| )] | |
| ax2.plot(refined_gens, delta, 'b-', linewidth=2) | |
| ax2.axhline(y=0, color='k', linestyle='--', alpha=0.5) | |
| ax2.fill_between(refined_gens, 0, delta, | |
| where=[d >= 0 for d in delta], alpha=0.3, color='green') | |
| ax2.fill_between(refined_gens, 0, delta, | |
| where=[d < 0 for d in delta], alpha=0.3, color='red') | |
| ax2.set_xlabel('Generation') | |
| ax2.set_ylabel('Score Difference') | |
| ax2.set_title('Refined - All Aux') | |
| ax2.grid(True, alpha=0.3) | |
| # Plot 3: Generation scores | |
| ax3 = fig.add_subplot(gs[1, 1]) | |
| ax3.plot(all_gens, all_aux_stats['scores'][:min_len], | |
| 'r-', alpha=0.6, label='All Aux (7)') | |
| ax3.plot(refined_gens, refined_stats['scores'][:min_len], | |
| 'g-', alpha=0.6, label='Refined (4)') | |
| ax3.set_xlabel('Generation') | |
| ax3.set_ylabel('Generation Best') | |
| ax3.set_title('Individual Generation Scores') | |
| ax3.legend() | |
| ax3.grid(True, alpha=0.3) | |
| # Plot 4: Cumulative improvement | |
| ax4 = fig.add_subplot(gs[1, 2]) | |
| all_improve = [(s - all_aux_stats['scores'][0]) | |
| for s in all_aux_stats['best_so_far'][:min_len]] | |
| refined_improve = [(s - refined_stats['scores'][0]) | |
| for s in refined_stats['best_so_far'][:min_len]] | |
| ax4.plot(all_gens, all_improve, 'r-', linewidth=2, label='All Aux (7)') | |
| ax4.plot(refined_gens, refined_improve, 'g-', linewidth=2, label='Refined (4)') | |
| ax4.set_xlabel('Generation') | |
| ax4.set_ylabel('Improvement from Start') | |
| ax4.set_title('Learning Progress') | |
| ax4.legend() | |
| ax4.grid(True, alpha=0.3) | |
| # Plot 5-7: Compare individual auxiliary metrics | |
| # Get common metrics | |
| all_aux_metrics = set() | |
| refined_aux_metrics = set() | |
| for prog in all_aux_data: | |
| all_aux_metrics.update(prog['aux_metrics'].keys()) | |
| for prog in refined_aux_data: | |
| refined_aux_metrics.update(prog['aux_metrics'].keys()) | |
| common_metrics = all_aux_metrics & refined_aux_metrics | |
| common_metrics = sorted(list(common_metrics))[:3] # Take first 3 | |
| for idx, metric in enumerate(common_metrics): | |
| ax = fig.add_subplot(gs[2, idx]) | |
| # Extract metric values | |
| all_values = [] | |
| all_gens_m = [] | |
| for prog in all_aux_data: | |
| if metric in prog['aux_metrics']: | |
| all_values.append(prog['aux_metrics'][metric]) | |
| all_gens_m.append(prog['generation']) | |
| refined_values = [] | |
| refined_gens_m = [] | |
| for prog in refined_aux_data: | |
| if metric in prog['aux_metrics']: | |
| refined_values.append(prog['aux_metrics'][metric]) | |
| refined_gens_m.append(prog['generation']) | |
| if all_values and refined_values: | |
| ax.plot(all_gens_m, all_values, 'r-', alpha=0.6, label='All Aux (7)') | |
| ax.plot(refined_gens_m, refined_values, 'g-', alpha=0.6, label='Refined (4)') | |
| ax.set_xlabel('Generation', fontsize=9) | |
| ax.set_ylabel('Metric Value', fontsize=9) | |
| ax.set_title(f'{metric}', fontsize=10) | |
| ax.legend(fontsize=8) | |
| ax.grid(True, alpha=0.3) | |
| # Save plot | |
| output_path = "my/aux_7vs4_comparison.png" | |
| plt.savefig(output_path, dpi=150, bbox_inches='tight') | |
| print(f"\nπΎ Plot saved to: {output_path}") | |
| return fig | |
| def main(): | |
| print("="*80) | |
| print("π¬ COMPARING AUXILIARY METRICS EXPERIMENTS") | |
| print("="*80) | |
| print("\nπ Experiments:") | |
| print(f" 1. All Aux (7): {ALL_AUX_DIR}") | |
| print(f" 2. Refined Aux (4): {REFINED_AUX_DIR}") | |
| # Load data | |
| print("\nβ³ Loading data...") | |
| all_aux_data = load_generation_data(ALL_AUX_DIR) | |
| refined_aux_data = load_generation_data(REFINED_AUX_DIR) | |
| print(f"β Loaded {len(all_aux_data)} generations from All Aux") | |
| print(f"β Loaded {len(refined_aux_data)} generations from Refined Aux") | |
| # Analyze auxiliary metrics | |
| analyze_aux_metrics(all_aux_data, "ALL AUX (7 metrics)") | |
| analyze_aux_metrics(refined_aux_data, "REFINED AUX (4 metrics)") | |
| # Compute statistics | |
| print(f"\n{'='*80}") | |
| print("π COMPUTING STATISTICS") | |
| print(f"{'='*80}") | |
| all_aux_stats = compute_stats(all_aux_data) | |
| refined_stats = compute_stats(refined_aux_data) | |
| # Print comparison | |
| print(f"\n{'='*80}") | |
| print("π PERFORMANCE COMPARISON") | |
| print(f"{'='*80}") | |
| all_final = all_aux_stats['best_so_far'][-1] | |
| refined_final = refined_stats['best_so_far'][-1] | |
| delta = refined_final - all_final | |
| rel_delta = 100 * delta / all_final | |
| print(f"\nπ΄ All Aux (7 metrics):") | |
| print(f" Final Score: {all_final:.4f}") | |
| print(f" Generations: {len(all_aux_data)}") | |
| print(f"\nπ’ Refined Aux (4 metrics):") | |
| print(f" Final Score: {refined_final:.4f}") | |
| print(f" Generations: {len(refined_aux_data)}") | |
| print(f"\nπ Difference:") | |
| print(f" Absolute: {delta:+.4f}") | |
| print(f" Relative: {rel_delta:+.2f}%") | |
| if delta > 0: | |
| print(f" β Refined is BETTER by {rel_delta:.2f}%") | |
| else: | |
| print(f" β Refined is WORSE by {abs(rel_delta):.2f}%") | |
| # Create plots | |
| print(f"\n{'='*80}") | |
| print("π CREATING PLOTS") | |
| print(f"{'='*80}") | |
| plot_comparison(all_aux_data, refined_aux_data, all_aux_stats, refined_stats) | |
| print(f"\n{'='*80}") | |
| print("β ANALYSIS COMPLETE") | |
| print(f"{'='*80}") | |
| print("\nπ‘ Key Findings:") | |
| print(f" β’ All Aux (7): {all_final:.4f}") | |
| print(f" β’ Refined Aux (4): {refined_final:.4f}") | |
| print(f" β’ Difference: {delta:+.4f} ({rel_delta:+.2f}%)") | |
| if delta < 0: | |
| print("\nβ οΈ WARNING: Refined Aux performed WORSE than All Aux!") | |
| print(" This suggests:") | |
| print(" 1. The removed 3 metrics may have been helpful") | |
| print(" 2. Or the 4 selected metrics provide misleading signals") | |
| print(" 3. Or correlation != causation") | |
| print() | |
| if __name__ == "__main__": | |
| main() | |