Download SMART/toy_example/softece_Experiment.py from zhurong2333/CaliBench: direct link, hf CLI and curl.
- Browser
- Download file 43.1 kB
-
https://huggingface.co/datasets/zhurong2333/CaliBench/resolve/main/SMART/toy_example/softece_Experiment.py
- Command line
-
hf download hf://datasets/zhurong2333/CaliBench/SMART/toy_example/softece_Experiment.py
-
curl -L -o softece_Experiment.py https://huggingface.co/datasets/zhurong2333/CaliBench/resolve/main/SMART/toy_example/softece_Experiment.py
43.1 kB
| import sys | |
| import os | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import matplotlib.pyplot as plt | |
| from tqdm import tqdm | |
| import json | |
| import time | |
| # Add the parent directory to the path to import from PureLogits | |
| current_dir = os.path.dirname(os.path.abspath(__file__)) | |
| parent_dir = os.path.dirname(current_dir) | |
| grandparent_dir = os.path.dirname(parent_dir) | |
| sys.path.append(grandparent_dir) | |
| sys.path.append(parent_dir) | |
| # Import necessary components from the calibrator | |
| from calibrator.Component.metrics import ( | |
| BrierLoss, CrossEntropyLoss, MSELoss, SoftECE, ECE | |
| ) | |
| # Set random seed for reproducibility | |
| def set_seed(seed): | |
| np.random.seed(seed) | |
| torch.manual_seed(seed) | |
| if torch.cuda.is_available(): | |
| torch.cuda.manual_seed(seed) | |
| torch.cuda.manual_seed_all(seed) | |
| torch.backends.cudnn.deterministic = True | |
| torch.backends.cudnn.benchmark = False | |
| # Load logits and labels from cache directory | |
| def load_data(cache_dir): | |
| val_logits = np.load(os.path.join(cache_dir, "val_logits.npy")) | |
| val_labels = np.load(os.path.join(cache_dir, "val_labels.npy")) | |
| test_logits = np.load(os.path.join(cache_dir, "test_logits.npy")) | |
| test_labels = np.load(os.path.join(cache_dir, "test_labels.npy")) | |
| print(f"Loaded data: val_logits shape: {val_logits.shape}, val_labels shape: {val_labels.shape}") | |
| print(f"Loaded data: test_logits shape: {test_logits.shape}, test_labels shape: {test_labels.shape}") | |
| return val_logits, val_labels, test_logits, test_labels | |
| # Compute hardness as the gap between top logit and runner-up | |
| def compute_hardness(logits): | |
| logits_tensor = torch.tensor(logits, dtype=torch.float32) | |
| sorted_logits, _ = torch.sort(logits_tensor, descending=True) | |
| logit_gap = (sorted_logits[0] - sorted_logits[1]).item() | |
| return logit_gap | |
| # Custom ECE wrapper to ensure it returns a tensor that can be backpropagated | |
| class ECEWrapper(nn.Module): | |
| def __init__(self, n_bins=15): | |
| super(ECEWrapper, self).__init__() | |
| self.ece = ECE(n_bins=n_bins) | |
| def forward(self, logits, labels): | |
| # ECE returns a scalar value, we need to wrap it in a tensor with requires_grad=True | |
| ece_value = self.ece(logits, labels) | |
| # Check if the result is already a tensor with grad | |
| if isinstance(ece_value, torch.Tensor) and ece_value.requires_grad: | |
| return ece_value | |
| # Otherwise, create a tensor with requires_grad=True | |
| if isinstance(ece_value, torch.Tensor): | |
| return ece_value.clone().detach().requires_grad_(True) | |
| else: | |
| return torch.tensor(ece_value, requires_grad=True, device=logits.device) | |
| # Custom Brier Loss implementation that ensures it's different from MSE | |
| class CustomBrierLoss(nn.Module): | |
| def __init__(self): | |
| super(CustomBrierLoss, self).__init__() | |
| def forward(self, logits, labels): | |
| # Get predicted probabilities | |
| outputs = F.softmax(logits, dim=1) | |
| # Convert labels to one-hot | |
| one_hot = torch.zeros(labels.size(0), outputs.size(1), device=labels.device) | |
| one_hot.scatter_(1, labels.unsqueeze(1), 1) | |
| # Compute Brier loss | |
| brier_score = torch.mean(torch.sum((outputs - one_hot) ** 2, dim=1)) | |
| # Explicitly scale by 0.5 to differentiate from MSE | |
| return brier_score * 0.5 | |
| # Experiment 1: Compare gradient stability of different calibration objectives | |
| def experiment_1_gradient_stability(test_logits, test_labels, cache_dir, output_dir="results"): | |
| print("\nExperiment 1: Comparing Gradient Stability of Different Calibration Objectives") | |
| # Create output directory | |
| os.makedirs(output_dir, exist_ok=True) | |
| # Convert data to PyTorch tensors | |
| logits_tensor = torch.tensor(test_logits, dtype=torch.float32) | |
| labels_tensor = torch.tensor(test_labels, dtype=torch.long) | |
| # Initialize different loss functions | |
| soft_ece = SoftECE(n_bins=15) | |
| traditional_ece = ECEWrapper(n_bins=15) # Use wrapper for ECE | |
| brier_score = BrierLoss() | |
| cross_entropy = CrossEntropyLoss() | |
| mse_loss = MSELoss() | |
| # Temperature parameter with gradient tracking | |
| temperature = nn.Parameter(torch.ones(1)) | |
| # Sample a subset of data for visualization (to avoid clutter) | |
| num_samples = 1000 | |
| indices = np.random.choice(len(test_logits), num_samples, replace=False) | |
| # Confidence bins for analysis | |
| confidence_bins = np.linspace(0.5, 1.0, 10) | |
| bin_width = confidence_bins[1] - confidence_bins[0] | |
| # Store gradients for each loss function across confidence levels | |
| results = { | |
| "SoftECE": {"grads": [], "conf_bins": []}, | |
| "ECE": {"grads": [], "conf_bins": []}, | |
| "Brier": {"grads": [], "conf_bins": []}, | |
| "CrossEntropy": {"grads": [], "conf_bins": []}, | |
| "MSE": {"grads": [], "conf_bins": []} | |
| } | |
| # Calculate gradients for different temperature values | |
| temp_values = [0.5, 0.8, 1.0, 1.2, 1.5, 2.0] | |
| for temp_val in temp_values: | |
| print(f"\nAnalyzing gradients at temperature = {temp_val}") | |
| # Set temperature to current value | |
| with torch.no_grad(): | |
| temperature.fill_(temp_val) | |
| # Process samples in batches to avoid memory issues | |
| batch_size = 100 | |
| num_batches = (num_samples + batch_size - 1) // batch_size | |
| for batch_idx in tqdm(range(num_batches)): | |
| start_idx = batch_idx * batch_size | |
| end_idx = min((batch_idx + 1) * batch_size, num_samples) | |
| batch_indices = indices[start_idx:end_idx] | |
| batch_logits = logits_tensor[batch_indices] | |
| batch_labels = labels_tensor[batch_indices] | |
| # Apply temperature scaling | |
| scaled_logits = batch_logits / temperature | |
| probs = F.softmax(scaled_logits, dim=1) | |
| # Calculate confidence (max probability) | |
| confidences = torch.max(probs, dim=1)[0].detach().numpy() | |
| # Calculate gradients for each loss function | |
| for loss_name, loss_fn in [ | |
| ("SoftECE", soft_ece), | |
| ("ECE", traditional_ece), | |
| ("Brier", brier_score), | |
| ("CrossEntropy", cross_entropy), | |
| ("MSE", mse_loss) | |
| ]: | |
| temperature.grad = None | |
| if loss_name == "SoftECE": | |
| loss = loss_fn(scaled_logits, batch_labels) | |
| elif loss_name == "ECE": | |
| loss = loss_fn(scaled_logits, batch_labels) | |
| elif loss_name == "Brier": | |
| loss = loss_fn(scaled_logits, batch_labels) | |
| elif loss_name == "CrossEntropy": | |
| loss = loss_fn(scaled_logits, batch_labels) | |
| elif loss_name == "MSE": | |
| loss = loss_fn(scaled_logits, batch_labels) | |
| loss.backward(retain_graph=True) | |
| # Store gradient magnitude for each sample | |
| if temperature.grad is not None: | |
| grad_magnitude = temperature.grad.item() | |
| # Store gradients by confidence bin | |
| for i, conf in enumerate(confidences): | |
| bin_idx = np.digitize(conf, confidence_bins) - 1 | |
| if 0 <= bin_idx < len(confidence_bins): | |
| results[loss_name]["grads"].append(grad_magnitude) | |
| results[loss_name]["conf_bins"].append(confidence_bins[bin_idx]) | |
| # Plot gradient magnitudes across confidence levels | |
| plt.figure(figsize=(10, 6)) | |
| for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]: | |
| # Group gradients by confidence bin | |
| binned_grads = {} | |
| for grad, bin_val in zip(results[loss_name]["grads"], results[loss_name]["conf_bins"]): | |
| if bin_val not in binned_grads: | |
| binned_grads[bin_val] = [] | |
| binned_grads[bin_val].append(grad) | |
| # Calculate mean and std of gradients for each bin | |
| bin_centers = [] | |
| mean_grads = [] | |
| std_grads = [] | |
| for bin_val in sorted(binned_grads.keys()): | |
| if binned_grads[bin_val]: # Ensure there are gradients for this bin | |
| bin_centers.append(bin_val) | |
| mean_grads.append(np.mean(np.abs(binned_grads[bin_val]))) | |
| std_grads.append(np.std(np.abs(binned_grads[bin_val]))) | |
| # Plot mean gradient magnitude with error bars | |
| plt.errorbar(bin_centers, mean_grads, yerr=std_grads, label=loss_name, marker='o', capsize=4) | |
| plt.xlabel('Confidence Level') | |
| plt.ylabel('Gradient Magnitude') | |
| plt.title('Gradient Stability Across Confidence Levels') | |
| plt.legend() | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'gradient_stability.png'), dpi=300) | |
| plt.close() | |
| # Save results | |
| with open(os.path.join(output_dir, 'gradient_stability_results.json'), 'w') as f: | |
| # Convert numpy arrays to lists for JSON serialization | |
| serializable_results = {} | |
| for loss_name, data in results.items(): | |
| serializable_results[loss_name] = { | |
| "grads": [float(g) for g in data["grads"]], | |
| "conf_bins": [float(c) for c in data["conf_bins"]] | |
| } | |
| json.dump(serializable_results, f, indent=2) | |
| print(f"Gradient stability analysis complete. Results saved to {output_dir}") | |
| # Experiment 2: Gradient information content analysis | |
| def experiment_2_gradient_information(test_logits, test_labels, cache_dir, output_dir="results"): | |
| print("\nExperiment 2: Analyzing Gradient Information Content of Different Calibration Objectives") | |
| # Create output directory | |
| os.makedirs(output_dir, exist_ok=True) | |
| # Convert data to PyTorch tensors | |
| logits_tensor = torch.tensor(test_logits, dtype=torch.float32) | |
| labels_tensor = torch.tensor(test_labels, dtype=torch.long) | |
| # Sample a subset of data | |
| num_samples = 2000 | |
| indices = np.random.choice(len(test_logits), num_samples, replace=False) | |
| # Initialize different loss functions | |
| soft_ece = SoftECE(n_bins=15, sigma=0.05) | |
| traditional_ece = ECEWrapper(n_bins=15) | |
| brier_score = BrierLoss() | |
| cross_entropy = CrossEntropyLoss() | |
| mse_loss = MSELoss() | |
| # Create synthetic miscalibration by distorting temperatures | |
| # We'll create 5 different scenarios ranging from underconfident to overconfident | |
| temp_scenarios = [0.5, 0.8, 1.0, 1.2, 2.0] | |
| # Store gradient direction consistency and correlation with calibration error | |
| results = { | |
| "temp_scenario": [], | |
| "ece_values": [], | |
| "gradient_consistency": {}, | |
| "gradient_correlation": {}, | |
| "gradient_entropy": {} | |
| } | |
| for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]: | |
| results["gradient_consistency"][loss_name] = [] | |
| results["gradient_correlation"][loss_name] = [] | |
| results["gradient_entropy"][loss_name] = [] | |
| # Create confidence bins for analysis | |
| confidence_bins = np.linspace(0.1, 1.0, 10) | |
| for temperature_value in temp_scenarios: | |
| print(f"\nAnalyzing scenario with temperature = {temperature_value}") | |
| # Set up temperature parameter for this scenario | |
| temperature = nn.Parameter(torch.ones(1) * temperature_value) | |
| # Generate scaled logits for the whole dataset to calculate overall ECE | |
| with torch.no_grad(): | |
| overall_scaled_logits = logits_tensor / temperature | |
| overall_probs = F.softmax(overall_scaled_logits, dim=1) | |
| ece_metric = ECE(n_bins=15) | |
| ece_value = ece_metric(overall_scaled_logits, labels_tensor).item() | |
| results["temp_scenario"].append(temperature_value) | |
| results["ece_values"].append(ece_value) | |
| print(f"Overall ECE for temperature {temperature_value}: {ece_value:.4f}") | |
| # For each loss function, analyze gradient properties | |
| for loss_name, loss_fn in [ | |
| ("SoftECE", soft_ece), | |
| ("ECE", traditional_ece), | |
| ("Brier", brier_score), | |
| ("CrossEntropy", cross_entropy), | |
| ("MSE", mse_loss) | |
| ]: | |
| print(f"Analyzing gradients for {loss_name}") | |
| # Calculate gradients for each sample in batches | |
| batch_size = 100 | |
| num_batches = (num_samples + batch_size - 1) // batch_size | |
| # Store all gradients and corresponding confidences | |
| all_grads = [] | |
| all_confidences = [] | |
| all_is_correct = [] | |
| for batch_idx in tqdm(range(num_batches)): | |
| start_idx = batch_idx * batch_size | |
| end_idx = min((batch_idx + 1) * batch_size, num_samples) | |
| batch_indices = indices[start_idx:end_idx] | |
| batch_logits = logits_tensor[batch_indices] | |
| batch_labels = labels_tensor[batch_indices] | |
| # Calculate gradients per sample | |
| for i in range(len(batch_logits)): | |
| sample_logits = batch_logits[i:i+1] | |
| sample_label = batch_labels[i:i+1] | |
| # Reset parameter to temperature_value for each sample | |
| temperature = nn.Parameter(torch.ones(1) * temperature_value) | |
| # Apply temperature scaling | |
| scaled_logits = sample_logits / temperature | |
| probs = F.softmax(scaled_logits, dim=1) | |
| # Check if prediction is correct | |
| pred = torch.argmax(probs, dim=1) | |
| is_correct = (pred == sample_label).float().item() | |
| # Calculate confidence | |
| confidence = torch.max(probs).item() | |
| # Calculate loss and gradient | |
| temperature.grad = None | |
| try: | |
| loss = loss_fn(scaled_logits, sample_label) | |
| loss.backward() | |
| # Only store if gradient was successfully calculated | |
| if temperature.grad is not None: | |
| all_grads.append(temperature.grad.item()) | |
| all_confidences.append(confidence) | |
| all_is_correct.append(is_correct) | |
| except Exception as e: | |
| # Skip samples that cause errors in gradient calculation | |
| print(f" Skipping sample due to error: {e}") | |
| continue | |
| # Skip further analysis if we don't have enough gradient data | |
| if len(all_grads) < 10: | |
| print(f" Not enough gradient data for {loss_name}, skipping analysis") | |
| continue | |
| # Calculate gradient consistency per confidence bin | |
| # (correlation between gradient direction and correctness) | |
| bin_grad_consistency = [] | |
| bin_grad_entropy = [] | |
| for i in range(len(confidence_bins) - 1): | |
| bin_start = confidence_bins[i] | |
| bin_end = confidence_bins[i+1] | |
| # Find samples in this bin | |
| bin_indices = [] | |
| for j in range(len(all_confidences)): | |
| if bin_start <= all_confidences[j] < bin_end: | |
| bin_indices.append(j) | |
| if len(bin_indices) > 5: # Only consider bins with enough samples | |
| bin_grads = [all_grads[j] for j in bin_indices] | |
| bin_correct = [all_is_correct[j] for j in bin_indices] | |
| # Calculate consistency: avg sign of gradient * (conf - accuracy) | |
| bin_conf = np.mean([all_confidences[j] for j in bin_indices]) | |
| bin_acc = np.mean(bin_correct) | |
| calibration_error = bin_conf - bin_acc | |
| # Compute correlation between gradient and calibration error | |
| # A well-behaved gradient should be negative when confidence > accuracy | |
| # and positive when confidence < accuracy | |
| grad_signs = np.sign(bin_grads) | |
| ce_sign = np.sign(calibration_error) | |
| correct_direction = -1 * ce_sign # Gradient should point in opposite direction of error | |
| consistency = np.mean(grad_signs == correct_direction) | |
| bin_grad_consistency.append(consistency) | |
| # Calculate entropy of gradient distribution in this bin | |
| # Normalize gradients for comparison | |
| if len(bin_grads) > 0 and np.std(bin_grads) > 0: | |
| norm_grads = (bin_grads - np.mean(bin_grads)) / np.std(bin_grads) | |
| # Use histogram to estimate entropy | |
| hist, _ = np.histogram(norm_grads, bins=10, density=True) | |
| hist = hist[hist > 0] # Avoid log(0) | |
| entropy = -np.sum(hist * np.log(hist)) | |
| bin_grad_entropy.append(entropy) | |
| # Store results | |
| if bin_grad_consistency: | |
| avg_consistency = np.mean(bin_grad_consistency) | |
| results["gradient_consistency"][loss_name].append(avg_consistency) | |
| print(f" {loss_name} gradient consistency: {avg_consistency:.4f}") | |
| if bin_grad_entropy: | |
| avg_entropy = np.mean(bin_grad_entropy) | |
| results["gradient_entropy"][loss_name].append(avg_entropy) | |
| print(f" {loss_name} gradient entropy: {avg_entropy:.4f}") | |
| # Calculate correlation between gradient and calibration error | |
| # For overall dataset | |
| if len(all_grads) > 0: | |
| accuracies = np.array(all_is_correct) | |
| confidences = np.array(all_confidences) | |
| grads = np.array(all_grads) | |
| # Ensure we have valid data | |
| if len(grads) > 0 and not np.all(np.isnan(grads)): | |
| cal_errors = confidences - accuracies | |
| # Correlation should be negative (gradient points opposite to error) | |
| correlation = np.corrcoef(cal_errors, -grads)[0, 1] | |
| if not np.isnan(correlation): | |
| results["gradient_correlation"][loss_name].append(correlation) | |
| print(f" {loss_name} gradient-error correlation: {correlation:.4f}") | |
| # Plot results | |
| # 1. Plot gradient consistency across different calibration scenarios | |
| plt.figure(figsize=(10, 6)) | |
| for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]: | |
| if loss_name in results["gradient_consistency"] and len(results["gradient_consistency"][loss_name]) > 0: | |
| plt.plot(results["temp_scenario"], results["gradient_consistency"][loss_name], | |
| marker='o', label=loss_name) | |
| plt.xlabel('Temperature (Lower = More Overconfident)') | |
| plt.ylabel('Gradient Direction Consistency') | |
| plt.title('Gradient Consistency Across Calibration Scenarios') | |
| plt.legend() | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'gradient_consistency.png'), dpi=300) | |
| plt.close() | |
| # 2. Plot gradient-error correlation | |
| plt.figure(figsize=(10, 6)) | |
| for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]: | |
| if loss_name in results["gradient_correlation"] and len(results["gradient_correlation"][loss_name]) > 0: | |
| plt.plot(results["temp_scenario"], results["gradient_correlation"][loss_name], | |
| marker='o', label=loss_name) | |
| plt.xlabel('Temperature (Lower = More Overconfident)') | |
| plt.ylabel('Correlation between Gradient and Calibration Error') | |
| plt.title('Gradient-Error Correlation Across Calibration Scenarios') | |
| plt.legend() | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'gradient_correlation.png'), dpi=300) | |
| plt.close() | |
| # 3. Plot gradient entropy (information content) | |
| plt.figure(figsize=(10, 6)) | |
| for loss_name in ["SoftECE", "ECE", "Brier", "CrossEntropy", "MSE"]: | |
| if loss_name in results["gradient_entropy"] and len(results["gradient_entropy"][loss_name]) > 0: | |
| plt.plot(results["temp_scenario"], results["gradient_entropy"][loss_name], | |
| marker='o', label=loss_name) | |
| plt.xlabel('Temperature (Lower = More Overconfident)') | |
| plt.ylabel('Gradient Distribution Entropy') | |
| plt.title('Gradient Information Content Across Calibration Scenarios') | |
| plt.legend() | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'gradient_entropy.png'), dpi=300) | |
| plt.close() | |
| # Save results | |
| with open(os.path.join(output_dir, 'gradient_information_results.json'), 'w') as f: | |
| # Ensure all data is serializable | |
| serializable_results = { | |
| "temp_scenario": list(results["temp_scenario"]), | |
| "ece_values": list(results["ece_values"]), | |
| "gradient_consistency": {k: list(v) for k, v in results["gradient_consistency"].items()}, | |
| "gradient_correlation": {k: list(v) for k, v in results["gradient_correlation"].items()}, | |
| "gradient_entropy": {k: list(v) for k, v in results["gradient_entropy"].items()} | |
| } | |
| json.dump(serializable_results, f, indent=2) | |
| print(f"Gradient information analysis complete. Results saved to {output_dir}") | |
| # Experiment 3: Sample efficiency and overfitting resistance analysis | |
| def experiment_3_sample_efficiency(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir="results"): | |
| print("\nExperiment 3: Analyzing Sample Efficiency and Overfitting Resistance") | |
| # Create output directory | |
| os.makedirs(output_dir, exist_ok=True) | |
| # Convert data to PyTorch tensors | |
| val_logits_tensor = torch.tensor(val_logits, dtype=torch.float32) | |
| val_labels_tensor = torch.tensor(val_labels, dtype=torch.long) | |
| test_logits_tensor = torch.tensor(test_logits, dtype=torch.float32) | |
| test_labels_tensor = torch.tensor(test_labels, dtype=torch.long) | |
| # Define different validation set sizes to test | |
| val_set_sizes = [10, 20, 30, 40,50, 100, 150] | |
| val_set_sizes = [min(size, len(val_logits)) for size in val_set_sizes] | |
| # Define loss functions to compare | |
| loss_functions = [ | |
| ("SoftECE", lambda: SoftECE(n_bins=15, sigma=0.05)), | |
| ("Brier", lambda: CustomBrierLoss()), | |
| ("CrossEntropy", lambda: CrossEntropyLoss()), | |
| ("MSE", lambda: MSELoss()) | |
| ] | |
| # Number of training steps to monitor | |
| max_steps = 100 | |
| step_interval = 5 # Record metrics every n steps | |
| # Store results | |
| results = { | |
| "val_set_sizes": val_set_sizes, | |
| "training_curves": {size: {} for size in val_set_sizes}, | |
| "final_metrics": {size: {} for size in val_set_sizes}, | |
| } | |
| # Train on different validation set sizes | |
| for val_size in val_set_sizes: | |
| print(f"\nTraining with validation set size: {val_size}") | |
| # Sample a subset of validation data | |
| indices = np.random.choice(len(val_logits), val_size, replace=False) | |
| subset_logits = val_logits_tensor[indices] | |
| subset_labels = val_labels_tensor[indices] | |
| # For each loss function | |
| for loss_name, loss_fn_creator in loss_functions: | |
| print(f" Training with {loss_name}") | |
| # Initialize results storage for this scenario | |
| if loss_name not in results["training_curves"][val_size]: | |
| results["training_curves"][val_size][loss_name] = { | |
| "steps": [], | |
| "train_loss": [], | |
| "train_ece": [], | |
| "test_ece": [], | |
| "test_acc": [] | |
| } | |
| if loss_name not in results["final_metrics"][val_size]: | |
| results["final_metrics"][val_size][loss_name] = {} | |
| # Initialize temperature and optimizer | |
| temperature = nn.Parameter(torch.ones(1)) | |
| optimizer = torch.optim.Adam([temperature], lr=0.01) | |
| # Create loss function | |
| loss_fn = loss_fn_creator() | |
| # Training loop with tracking | |
| for step in range(max_steps): | |
| optimizer.zero_grad() | |
| # Apply temperature scaling | |
| scaled_logits = subset_logits / temperature | |
| # Calculate loss | |
| loss = loss_fn(scaled_logits, subset_labels) | |
| # Backpropagation | |
| loss.backward() | |
| optimizer.step() | |
| # Record metrics at specified intervals | |
| if step % step_interval == 0 or step == max_steps - 1: | |
| with torch.no_grad(): | |
| # Calculate training metrics | |
| train_ece = ECE(n_bins=15)(scaled_logits, subset_labels).item() | |
| # Calculate test metrics | |
| test_scaled_logits = test_logits_tensor / temperature | |
| test_probs = F.softmax(test_scaled_logits, dim=1) | |
| test_ece = ECE(n_bins=15)(test_scaled_logits, test_labels_tensor).item() | |
| test_acc = (torch.argmax(test_probs, dim=1) == test_labels_tensor).float().mean().item() | |
| # Store metrics | |
| results["training_curves"][val_size][loss_name]["steps"].append(step) | |
| results["training_curves"][val_size][loss_name]["train_loss"].append(loss.item()) | |
| results["training_curves"][val_size][loss_name]["train_ece"].append(train_ece) | |
| results["training_curves"][val_size][loss_name]["test_ece"].append(test_ece) | |
| results["training_curves"][val_size][loss_name]["test_acc"].append(test_acc) | |
| # Store final metrics | |
| results["final_metrics"][val_size][loss_name] = { | |
| "temperature": temperature.item(), | |
| "train_ece": train_ece, | |
| "test_ece": test_ece, | |
| "test_acc": test_acc, | |
| "train_test_ece_gap": abs(train_ece - test_ece) # Measure of overfitting | |
| } | |
| print(f" Final temperature: {temperature.item():.4f}, Test ECE: {test_ece:.4f}") | |
| # Plot results | |
| # 1. Plot final test ECE vs validation set size | |
| plt.figure(figsize=(10, 6)) | |
| print("\nFinal Test ECE values for plotting:") | |
| for loss_name, _ in loss_functions: | |
| test_eces = [results["final_metrics"][size][loss_name]["test_ece"] for size in val_set_sizes] | |
| print(f" {loss_name}: {test_eces}") | |
| line, = plt.plot(val_set_sizes, test_eces, marker='o', linewidth=2, markersize=8) | |
| plt.annotate(loss_name, (val_set_sizes[-1], test_eces[-1]), | |
| xytext=(5, 0), textcoords='offset points', va='center') | |
| plt.xlabel('Validation Set Size') | |
| plt.ylabel('Test ECE') | |
| plt.title('Sample Efficiency: Test ECE vs. Validation Set Size') | |
| plt.legend([loss_name for loss_name, _ in loss_functions]) | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'sample_efficiency_ece.png'), dpi=300) | |
| plt.close() | |
| # 2. Plot train-test ECE gap vs validation set size (measure of overfitting) | |
| plt.figure(figsize=(10, 6)) | |
| print("\nTrain-Test ECE Gap values for plotting:") | |
| for loss_name, _ in loss_functions: | |
| gaps = [results["final_metrics"][size][loss_name]["train_test_ece_gap"] for size in val_set_sizes] | |
| print(f" {loss_name}: {gaps}") | |
| line, = plt.plot(val_set_sizes, gaps, marker='o', linewidth=2, markersize=8) | |
| plt.annotate(loss_name, (val_set_sizes[-1], gaps[-1]), | |
| xytext=(5, 0), textcoords='offset points', va='center') | |
| plt.xlabel('Validation Set Size') | |
| plt.ylabel('|Train ECE - Test ECE|') | |
| plt.title('Overfitting Resistance: Train-Test Gap vs. Validation Set Size') | |
| plt.legend([loss_name for loss_name, _ in loss_functions]) | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'overfitting_resistance.png'), dpi=300) | |
| plt.close() | |
| # 3. Plot training curves for different loss functions on smallest dataset | |
| smallest_size = val_set_sizes[0] | |
| plt.figure(figsize=(12, 8)) | |
| for loss_name, _ in loss_functions: | |
| steps = results["training_curves"][smallest_size][loss_name]["steps"] | |
| test_eces = results["training_curves"][smallest_size][loss_name]["test_ece"] | |
| plt.plot(steps, test_eces, marker='.', label=f"{loss_name}") | |
| plt.xlabel('Training Step') | |
| plt.ylabel('Test ECE') | |
| plt.title(f'Training Stability with Small Dataset (n={smallest_size})') | |
| plt.legend() | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, f'training_stability_{smallest_size}.png'), dpi=300) | |
| plt.close() | |
| # 4. Plot training curves for SoftECE across different dataset sizes | |
| plt.figure(figsize=(12, 8)) | |
| for val_size in val_set_sizes: | |
| steps = results["training_curves"][val_size]["SoftECE"]["steps"] | |
| test_eces = results["training_curves"][val_size]["SoftECE"]["test_ece"] | |
| plt.plot(steps, test_eces, marker='.', label=f"n={val_size}") | |
| plt.xlabel('Training Step') | |
| plt.ylabel('Test ECE') | |
| plt.title('SoftECE Training Curves Across Dataset Sizes') | |
| plt.legend() | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'softece_across_sizes.png'), dpi=300) | |
| plt.close() | |
| # Save results | |
| with open(os.path.join(output_dir, 'sample_efficiency_results.json'), 'w') as f: | |
| # Ensure all data is serializable | |
| serializable_results = { | |
| "val_set_sizes": results["val_set_sizes"], | |
| "training_curves": {}, | |
| "final_metrics": {} | |
| } | |
| # Convert training curves | |
| for size in results["training_curves"]: | |
| serializable_results["training_curves"][str(size)] = {} | |
| for loss_name in results["training_curves"][size]: | |
| serializable_results["training_curves"][str(size)][loss_name] = { | |
| k: [float(v_i) for v_i in v] | |
| for k, v in results["training_curves"][size][loss_name].items() | |
| } | |
| # Convert final metrics | |
| for size in results["final_metrics"]: | |
| serializable_results["final_metrics"][str(size)] = {} | |
| for loss_name in results["final_metrics"][size]: | |
| serializable_results["final_metrics"][str(size)][loss_name] = { | |
| k: float(v) for k, v in results["final_metrics"][size][loss_name].items() | |
| } | |
| json.dump(serializable_results, f, indent=2) | |
| print(f"Sample efficiency analysis complete. Results saved to {output_dir}") | |
| # Experiment 4: Bias-variance tradeoff visualization | |
| def experiment_4_bias_variance_tradeoff(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir="results"): | |
| print("\nExperiment 4: Visualizing Bias-Variance Tradeoff") | |
| # Create output directory | |
| os.makedirs(output_dir, exist_ok=True) | |
| # Convert data to PyTorch tensors | |
| val_logits_tensor = torch.tensor(val_logits, dtype=torch.float32) | |
| val_labels_tensor = torch.tensor(val_labels, dtype=torch.long) | |
| test_logits_tensor = torch.tensor(test_logits, dtype=torch.float32) | |
| test_labels_tensor = torch.tensor(test_labels, dtype=torch.long) | |
| # Define loss functions to compare | |
| loss_functions = [ | |
| ("SoftECE", lambda: SoftECE(n_bins=15, sigma=0.05)), | |
| ("ECE", lambda: ECEWrapper(n_bins=15)), | |
| ("Brier", lambda: CustomBrierLoss()), | |
| ("CrossEntropy", lambda: CrossEntropyLoss()), | |
| ("MSE", lambda: MSELoss()) | |
| ] | |
| # Bootstrap parameters | |
| n_bootstraps = 20 # Number of bootstrap samples | |
| bootstrap_size = min(500, len(val_logits)) # Size of each bootstrap sample | |
| # Store results | |
| results = { | |
| "bootstrap_metrics": {loss_name: { | |
| "temperatures": [], | |
| "test_eces": [], | |
| "calibrated_confidences": [] | |
| } for loss_name, _ in loss_functions}, | |
| "aggregated_metrics": {loss_name: {} for loss_name, _ in loss_functions} | |
| } | |
| # Create bootstrap samples | |
| print(f"Creating {n_bootstraps} bootstrap samples of size {bootstrap_size}") | |
| bootstrap_indices = [] | |
| for i in range(n_bootstraps): | |
| # Sample with replacement | |
| indices = np.random.choice(len(val_logits), bootstrap_size, replace=True) | |
| bootstrap_indices.append(indices) | |
| # Train on each bootstrap sample | |
| for bootstrap_idx, indices in enumerate(bootstrap_indices): | |
| print(f"\nTraining on bootstrap sample {bootstrap_idx+1}/{n_bootstraps}") | |
| # Get bootstrap sample | |
| bootstrap_logits = val_logits_tensor[indices] | |
| bootstrap_labels = val_labels_tensor[indices] | |
| # Train each loss function on this bootstrap sample | |
| for loss_name, loss_fn_creator in loss_functions: | |
| # Initialize temperature and optimizer | |
| temperature = nn.Parameter(torch.ones(1)) | |
| optimizer = torch.optim.Adam([temperature], lr=0.01) | |
| # Create loss function | |
| loss_fn = loss_fn_creator() | |
| # Train for a fixed number of epochs | |
| epochs = 100 | |
| for epoch in range(epochs): | |
| optimizer.zero_grad() | |
| # Apply temperature scaling | |
| scaled_logits = bootstrap_logits / temperature | |
| # Calculate loss | |
| loss = loss_fn(scaled_logits, bootstrap_labels) | |
| # Backpropagation | |
| loss.backward() | |
| optimizer.step() | |
| # Evaluate on test set | |
| with torch.no_grad(): | |
| # Apply learned temperature | |
| scaled_test_logits = test_logits_tensor / temperature | |
| test_probs = F.softmax(scaled_test_logits, dim=1) | |
| # Calculate metrics | |
| test_ece = ECE(n_bins=15)(scaled_test_logits, test_labels_tensor).item() | |
| # Store max confidences from a random subset for visualization | |
| subset_size = min(1000, len(test_logits)) | |
| subset_indices = np.random.choice(len(test_logits), subset_size, replace=False) | |
| subset_confs = torch.max(test_probs[subset_indices], dim=1)[0].cpu().numpy() | |
| # Store results for this bootstrap run | |
| results["bootstrap_metrics"][loss_name]["temperatures"].append(temperature.item()) | |
| results["bootstrap_metrics"][loss_name]["test_eces"].append(test_ece) | |
| results["bootstrap_metrics"][loss_name]["calibrated_confidences"].append(subset_confs) | |
| print(f" {loss_name}: Temperature = {temperature.item():.4f}, Test ECE = {test_ece:.4f}") | |
| # Calculate aggregated metrics | |
| for loss_name, _ in loss_functions: | |
| temps = results["bootstrap_metrics"][loss_name]["temperatures"] | |
| eces = results["bootstrap_metrics"][loss_name]["test_eces"] | |
| # Calculate statistics | |
| results["aggregated_metrics"][loss_name] = { | |
| "temperature_mean": np.mean(temps), | |
| "temperature_std": np.std(temps), | |
| "temperature_cv": np.std(temps) / np.mean(temps) if np.mean(temps) > 0 else 0, # Coefficient of variation | |
| "ece_mean": np.mean(eces), | |
| "ece_std": np.std(eces), | |
| "ece_cv": np.std(eces) / np.mean(eces) if np.mean(eces) > 0 else 0 | |
| } | |
| # Prepare plots | |
| # 1. Box plots of learned temperatures | |
| plt.figure(figsize=(10, 6)) | |
| temp_data = [results["bootstrap_metrics"][loss_name]["temperatures"] for loss_name, _ in loss_functions] | |
| plt.boxplot(temp_data, labels=[loss_name for loss_name, _ in loss_functions]) | |
| plt.ylabel('Temperature Value') | |
| plt.title('Distribution of Learned Temperatures Across Bootstrap Samples') | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'temperature_distribution.png'), dpi=300) | |
| plt.close() | |
| # 2. Box plots of test ECEs | |
| plt.figure(figsize=(10, 6)) | |
| ece_data = [results["bootstrap_metrics"][loss_name]["test_eces"] for loss_name, _ in loss_functions] | |
| plt.boxplot(ece_data, labels=[loss_name for loss_name, _ in loss_functions]) | |
| plt.ylabel('Test ECE') | |
| plt.title('Distribution of Test ECE Across Bootstrap Samples') | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'ece_distribution.png'), dpi=300) | |
| plt.close() | |
| # 3. Scatter plot of temperature variance vs ECE mean | |
| plt.figure(figsize=(10, 6)) | |
| temp_vars = [results["aggregated_metrics"][loss_name]["temperature_cv"] for loss_name, _ in loss_functions] | |
| ece_means = [results["aggregated_metrics"][loss_name]["ece_mean"] for loss_name, _ in loss_functions] | |
| plt.scatter(temp_vars, ece_means, s=100) | |
| # Add labels to points | |
| for i, (loss_name, _) in enumerate(loss_functions): | |
| plt.annotate(loss_name, (temp_vars[i], ece_means[i]), | |
| textcoords="offset points", xytext=(0,10), ha='center') | |
| plt.xlabel('Temperature Coefficient of Variation') | |
| plt.ylabel('Mean Test ECE') | |
| plt.title('Bias-Variance Tradeoff: Parameter Stability vs. Calibration Performance') | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'bias_variance_tradeoff.png'), dpi=300) | |
| plt.close() | |
| # 4. Histograms of calibrated confidences for each method | |
| # We'll use the last bootstrap sample for visualization | |
| plt.figure(figsize=(15, 10)) | |
| for i, (loss_name, _) in enumerate(loss_functions): | |
| plt.subplot(2, 3, i+1) | |
| confidences = results["bootstrap_metrics"][loss_name]["calibrated_confidences"][-1] | |
| plt.hist(confidences, bins=20, alpha=0.7) | |
| plt.title(f'{loss_name} Calibrated Confidences') | |
| plt.xlabel('Confidence') | |
| plt.ylabel('Count') | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'calibrated_confidence_distribution.png'), dpi=300) | |
| plt.close() | |
| # 5. Violin plots of ECE distribution | |
| plt.figure(figsize=(12, 6)) | |
| # Create violin plot | |
| plt.violinplot(ece_data, showmeans=True, showmedians=True) | |
| # Add labels | |
| plt.xticks(range(1, len(loss_functions) + 1), [loss_name for loss_name, _ in loss_functions]) | |
| plt.ylabel('Test ECE') | |
| plt.title('Density Distribution of Test ECE Across Bootstrap Samples') | |
| plt.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(output_dir, 'ece_density_distribution.png'), dpi=300) | |
| plt.close() | |
| # Save results | |
| with open(os.path.join(output_dir, 'bias_variance_results.json'), 'w') as f: | |
| # Ensure all data is serializable | |
| serializable_results = { | |
| "bootstrap_metrics": {}, | |
| "aggregated_metrics": {} | |
| } | |
| # Convert bootstrap metrics | |
| for loss_name in results["bootstrap_metrics"]: | |
| serializable_results["bootstrap_metrics"][loss_name] = { | |
| "temperatures": [float(t) for t in results["bootstrap_metrics"][loss_name]["temperatures"]], | |
| "test_eces": [float(e) for e in results["bootstrap_metrics"][loss_name]["test_eces"]], | |
| # Don't save all confidences as it's too much data | |
| "temperature_mean": float(np.mean(results["bootstrap_metrics"][loss_name]["temperatures"])), | |
| "temperature_std": float(np.std(results["bootstrap_metrics"][loss_name]["temperatures"])), | |
| "ece_mean": float(np.mean(results["bootstrap_metrics"][loss_name]["test_eces"])), | |
| "ece_std": float(np.std(results["bootstrap_metrics"][loss_name]["test_eces"])) | |
| } | |
| # Convert aggregated metrics | |
| for loss_name in results["aggregated_metrics"]: | |
| serializable_results["aggregated_metrics"][loss_name] = { | |
| k: float(v) for k, v in results["aggregated_metrics"][loss_name].items() | |
| } | |
| json.dump(serializable_results, f, indent=2) | |
| print(f"Bias-variance tradeoff analysis complete. Results saved to {output_dir}") | |
| def main(): | |
| # Set random seed | |
| set_seed(42) | |
| # Define cache directory containing logits and labels | |
| cache_dir = "/hdd/haolan/shats/PureLogits/cache/imagenet_vit_b_16_seed1_vs0.2" | |
| # cache_dir = "/hdd/haolan/shats/PureLogits/cache/cifar100_resnet50_cross_entropy_seed1" | |
| # cache_dir = "/hdd/haolan/shats/PureLogits/cache/imagenet_resnet50_seed1_vs0.2" | |
| # cache_dir = "/hdd/haolan/shats/PureLogits/cache/cifar10_resnet50_cross_entropy_seed1" | |
| # Load data | |
| val_logits, val_labels, test_logits, test_labels = load_data(cache_dir) | |
| # Create output directory | |
| output_dir = "experiment_results/softece_validation" | |
| os.makedirs(output_dir, exist_ok=True) | |
| # Run experiments | |
| # experiment_1_gradient_stability(test_logits, test_labels, cache_dir, output_dir) | |
| # experiment_2_gradient_information(test_logits, test_labels, cache_dir, output_dir) | |
| experiment_3_sample_efficiency(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir) | |
| # experiment_4_bias_variance_tradeoff(val_logits, val_labels, test_logits, test_labels, cache_dir, output_dir) | |
| if __name__ == "__main__": | |
| start_time = time.time() | |
| main() | |
| elapsed_time = time.time() - start_time | |
| print(f"Experiments completed in {elapsed_time/60:.2f} minutes") |