import matplotlib.pyplot as plt import torch import numpy as np from mpl_toolkits.mplot3d import Axes3D import os def plot_losses(losses, title="Training Loss", xlabel="Iteration", ylabel="Loss", save_path=None): """ Plot training losses. Args: losses (list): List of loss values title (str): Plot title xlabel (str): X-axis label ylabel (str): Y-axis label save_path (str): Optional path to save the figure """ plt.figure(figsize=(10, 6)) plt.plot(losses, 'o-') plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) if save_path: plt.savefig(save_path) print(f"Loss plot saved to {save_path}") plt.show() def plot_multiple_losses(loss_dict, title="Training Losses", xlabel="Iteration", ylabel="Loss", save_path=None): """ Plot multiple loss curves for comparison. Args: loss_dict (dict): Dictionary mapping loss names to lists of loss values title (str): Plot title xlabel (str): X-axis label ylabel (str): Y-axis label save_path (str): Optional path to save the figure """ plt.figure(figsize=(12, 7)) for name, losses in loss_dict.items(): plt.plot(losses, '-', label=name) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) plt.legend() if save_path: plt.savefig(save_path) print(f"Multiple losses plot saved to {save_path}") plt.show() def plot_multiple_accuracies(acc_dict, title="Classification Accuracy", xlabel="Percent Labeled", ylabel="Accuracy", save_path=None): """ Plot multiple accuracy curves for comparison. Args: acc_dict (dict): Dictionary mapping method names to [x_values, accuracy_values] title (str): Plot title xlabel (str): X-axis label ylabel (str): Y-axis label save_path (str): Optional path to save the figure """ plt.figure(figsize=(14, 8)) markers = ['o', 's', '^', 'v', 'd', '*', 'x', '+', 'h', 'p'] colors = plt.cm.tab10.colors for i, (name, (x_values, acc_values)) in enumerate(acc_dict.items()): marker = markers[i % len(markers)] color = colors[i % len(colors)] plt.plot(x_values, acc_values, marker=marker, color=color, linewidth=2, markersize=8, label=name) plt.xlabel(xlabel, fontsize=14) plt.ylabel(ylabel, fontsize=14) plt.title(title, fontsize=16) plt.grid(True) plt.legend(fontsize=12) plt.ylim(0, 1) if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Accuracy comparison plot saved to {save_path}") plt.show() def plot_swiss_roll_3d(xyz, labels, title="Swiss Roll in 3D", save_path=None, figsize=(10, 8)): """ Plot 3D Swiss roll with color-coded labels. Args: xyz (numpy.ndarray): 3D coordinates of points labels (numpy.ndarray): Labels for coloring points title (str): Plot title save_path (str): Optional path to save the figure figsize (tuple): Figure size """ fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='3d') scatter = ax.scatter( xyz[:, 0], xyz[:, 1], xyz[:, 2], c=labels, cmap='bwr', s=40 ) legend = ax.legend(*scatter.legend_elements(), title="Classes") ax.add_artist(legend) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.set_title(title) if save_path: plt.savefig(save_path) print(f"3D plot saved to {save_path}") plt.show() def plot_laplacian_comparison(real_lap, pred_lap, title="Laplacian Comparison", save_path=None): """ Plot comparison between real and predicted Laplacian matrices. Args: real_lap (numpy.ndarray): Real Laplacian matrix pred_lap (numpy.ndarray): Predicted Laplacian matrix title (str): Plot title save_path (str): Optional path to save the figure """ # Convert to numpy if tensors if isinstance(real_lap, torch.Tensor): real_lap = real_lap.cpu().numpy() if isinstance(pred_lap, torch.Tensor): pred_lap = pred_lap.cpu().numpy() diff = pred_lap - real_lap fig, axs = plt.subplots(1, 3, figsize=(18, 6)) # Plot real Laplacian im0 = axs[0].imshow(real_lap, cmap='viridis') axs[0].set_title("Real Laplacian") plt.colorbar(im0, ax=axs[0]) # Plot predicted Laplacian im1 = axs[1].imshow(pred_lap, cmap='viridis') axs[1].set_title("Predicted Laplacian") plt.colorbar(im1, ax=axs[1]) # Plot difference im2 = axs[2].imshow(diff, cmap='bwr') axs[2].set_title("Difference (Predicted - Real)") plt.colorbar(im2, ax=axs[2]) plt.suptitle(title, fontsize=16) plt.tight_layout() if save_path: plt.savefig(save_path) print(f"Laplacian comparison plot saved to {save_path}") plt.show() # Return Frobenius norm of the difference return np.sqrt(np.sum(diff**2)) def plot_eigenvector_comparison(real_evecs, pred_evecs, k=3, title="Eigenvector Comparison", save_path=None): """ Plot comparison between real and predicted eigenvectors. Args: real_evecs (numpy.ndarray): Real eigenvectors pred_evecs (numpy.ndarray): Predicted eigenvectors k (int): Number of eigenvectors to plot title (str): Plot title save_path (str): Optional path to save the figure """ # Convert to numpy if tensors if isinstance(real_evecs, torch.Tensor): real_evecs = real_evecs.cpu().numpy() if isinstance(pred_evecs, torch.Tensor): pred_evecs = pred_evecs.cpu().numpy() # Normalize eigenvectors real_evecs_norm = real_evecs / np.linalg.norm(real_evecs, axis=0, keepdims=True) pred_evecs_norm = pred_evecs / np.linalg.norm(pred_evecs, axis=0, keepdims=True) # Plot comparisons fig, axs = plt.subplots(k, 1, figsize=(10, 4*k)) if k == 1: axs = [axs] for i in range(k): # Handle sign ambiguity corr_pos = np.corrcoef(real_evecs_norm[:, i], pred_evecs_norm[:, i])[0, 1] corr_neg = np.corrcoef(real_evecs_norm[:, i], -pred_evecs_norm[:, i])[0, 1] pred_ev_to_plot = -pred_evecs_norm[:, i] if abs(corr_neg) > abs(corr_pos) else pred_evecs_norm[:, i] corr = max(abs(corr_pos), abs(corr_neg)) axs[i].plot(real_evecs_norm[:, i], 'b-', label='Real') axs[i].plot(pred_ev_to_plot, 'r--', label='Predicted') axs[i].grid(True) axs[i].set_title(f"Eigenvector {i+1} (Correlation: {corr:.4f})") axs[i].legend() plt.suptitle(title, fontsize=16) plt.tight_layout() if save_path: plt.savefig(save_path) print(f"Eigenvector comparison plot saved to {save_path}") plt.show() def plot_embedding_3d(embeddings, labels, title="3D Embedding", save_path=None): """ Plot 3D embedding of points with color-coded labels. Args: embeddings (numpy.ndarray): Embedding coordinates (n_samples, 3) labels (numpy.ndarray): Labels for coloring points title (str): Plot title save_path (str): Optional path to save the figure """ fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') scatter = ax.scatter( embeddings[:, 0], embeddings[:, 1], embeddings[:, 2], c=labels, cmap='bwr', s=40 ) legend = ax.legend(*scatter.legend_elements(), title="Classes") ax.add_artist(legend) ax.set_xlabel("Component 1") ax.set_ylabel("Component 2") ax.set_zlabel("Component 3") ax.set_title(title) if save_path: plt.savefig(save_path) print(f"3D embedding plot saved to {save_path}") plt.show() def create_multi_embedding_plot(embeddings_dict, labels, title="Embedding Comparison", save_path=None): """ Create a multi-panel plot comparing different embeddings. Args: embeddings_dict (dict): Dictionary mapping names to embedding arrays labels (numpy.ndarray): Labels for coloring points title (str): Plot title save_path (str): Optional path to save the figure """ n_embeddings = len(embeddings_dict) n_cols = min(3, n_embeddings) n_rows = (n_embeddings + n_cols - 1) // n_cols fig = plt.figure(figsize=(6*n_cols, 5*n_rows)) for i, (name, embedding) in enumerate(embeddings_dict.items()): ax = fig.add_subplot(n_rows, n_cols, i+1, projection='3d') scatter = ax.scatter( embedding[:, 0], embedding[:, 1], embedding[:, 2], c=labels, cmap='bwr', s=30 ) if i == 0: legend = ax.legend(*scatter.legend_elements(), title="Classes") ax.add_artist(legend) ax.set_xlabel("Component 1") ax.set_ylabel("Component 2") ax.set_zlabel("Component 3") ax.set_title(name) plt.suptitle(title, fontsize=16) plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust for the super title if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Multi-embedding plot saved to {save_path}") plt.show() def plot_accuracy_vs_context(acc_results, title="Accuracy vs Context Size", xlabel="Context Size", ylabel="Accuracy", save_path=None): """ Plot accuracy as a function of context size. Args: acc_results (dict): Dictionary mapping context size to accuracy title (str): Plot title xlabel (str): X-axis label ylabel (str): Y-axis label save_path (str): Optional path to save the figure """ import matplotlib.pyplot as plt # Extract data context_sizes = sorted(acc_results.keys()) accuracies = [acc_results[c] for c in context_sizes] # Create plot plt.figure(figsize=(10, 6)) plt.plot(context_sizes, accuracies, 'o-', linewidth=2, markersize=8) plt.xlabel(xlabel, fontsize=14) plt.ylabel(ylabel, fontsize=14) plt.title(title, fontsize=16) plt.grid(True) plt.ylim(0, 1) # Add specific annotations for min and max accuracies min_acc = min(accuracies) max_acc = max(accuracies) min_idx = accuracies.index(min_acc) max_idx = accuracies.index(max_acc) plt.annotate(f'Min: {min_acc:.3f}', xy=(context_sizes[min_idx], min_acc), xytext=(10, 20), textcoords='offset points', arrowprops=dict(arrowstyle='->')) plt.annotate(f'Max: {max_acc:.3f}', xy=(context_sizes[max_idx], max_acc), xytext=(10, -20), textcoords='offset points', arrowprops=dict(arrowstyle='->')) if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Accuracy vs context plot saved to {save_path}") plt.show() def plot_embedding_comparison(raw_coords, embedding, labels, title="Embedding Comparison", save_path=None): """ Create side-by-side plots comparing raw coordinates with embedding. Args: raw_coords (numpy.ndarray): Raw coordinates [n_samples, 2] embedding (numpy.ndarray): Embedding coordinates [n_samples, n_components] labels (numpy.ndarray): Labels for coloring points title (str): Plot title save_path (str): Optional path to save the figure """ import matplotlib.pyplot as plt import numpy as np # Create figure fig, axs = plt.subplots(1, 2, figsize=(14, 6)) # Plot raw coordinates scatter1 = axs[0].scatter( raw_coords[:, 0], raw_coords[:, 1], c=labels, cmap='bwr', s=40, alpha=0.8 ) axs[0].set_xlabel("X") axs[0].set_ylabel("Y") axs[0].set_title("Raw Coordinates") axs[0].grid(True) # Plot embedding (first 2 components) if embedding.shape[1] >= 2: scatter2 = axs[1].scatter( embedding[:, 0], embedding[:, 1], c=labels, cmap='bwr', s=40, alpha=0.8 ) axs[1].set_xlabel("Component 1") axs[1].set_ylabel("Component 2") axs[1].set_title("Embedding") axs[1].grid(True) # Add legend legend = axs[0].legend(*scatter1.legend_elements(), title="Classes") axs[0].add_artist(legend) plt.suptitle(title, fontsize=16) plt.tight_layout() if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Embedding comparison plot saved to {save_path}") plt.show() def plot_swiss_roll_colored_by_embedding(xyz, embedding, component_idx=0, title="Swiss Roll Colored by Embedding", save_path=None): """ Plot 3D Swiss roll colored by embedding component values. Args: xyz (numpy.ndarray): 3D coordinates of points embedding (numpy.ndarray): Embedding values component_idx (int): Index of embedding component to use for coloring title (str): Plot title save_path (str): Optional path to save the figure """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # Extract the selected component if embedding.ndim > 1: color_values = embedding[:, component_idx] else: color_values = embedding # Normalize values for coloring normalized_values = (color_values - np.min(color_values)) / (np.max(color_values) - np.min(color_values)) fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') scatter = ax.scatter( xyz[:, 0], xyz[:, 1], xyz[:, 2], c=normalized_values, cmap='viridis', s=40 ) # Add a color bar cbar = plt.colorbar(scatter) cbar.set_label(f"Normalized Component {component_idx+1} Values") ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.set_title(title) if save_path: plt.savefig(save_path) print(f"3D embedding plot saved to {save_path}") plt.show() import matplotlib.pyplot as plt import numpy as np import os import datetime def plot_test_results(args, results, n_samples=100, figure_dir='../figures'): """ Plot test results across different context sizes. Args: args: Command line arguments containing test_mode, data_type, etc. results: Dictionary containing the test results for each context size n_samples: Total number of samples per graph figure_dir: Directory to save the figures """ # Create timestamp for unique filenames timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") # Create directory structure based on test_mode and data_type specific_dir = os.path.join(figure_dir, f"test_mode_{args.test_mode}", f"data_{args.data_type}") os.makedirs(specific_dir, exist_ok=True) # Extract context sizes and convert to percentages context_sizes = list(results.keys()) context_percentages = [ctx_size / n_samples * 100 for ctx_size in context_sizes] # Extract average accuracies and standard deviations for each method avg_icl = [sum(results[ctx]['icl_accs']) / len(results[ctx]['icl_accs']) for ctx in context_sizes] avg_lr = [sum(results[ctx]['lr_accs']) / len(results[ctx]['lr_accs']) for ctx in context_sizes] avg_rkhs = [sum(results[ctx]['rkhs_accs']) / len(results[ctx]['rkhs_accs']) for ctx in context_sizes] avg_raw_lr = [sum(results[ctx]['raw_lr_accs']) / len(results[ctx]['raw_lr_accs']) for ctx in context_sizes] avg_raw_rkhs = [sum(results[ctx]['raw_rkhs_accs']) / len(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes] std_icl = [np.std(results[ctx]['icl_accs']) for ctx in context_sizes] std_lr = [np.std(results[ctx]['lr_accs']) for ctx in context_sizes] std_rkhs = [np.std(results[ctx]['rkhs_accs']) for ctx in context_sizes] std_raw_lr = [np.std(results[ctx]['raw_lr_accs']) for ctx in context_sizes] std_raw_rkhs = [np.std(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes] # Generate a base filename with test details base_filename = f"mode_{args.test_mode}_data_{args.data_type}_samples_{n_samples}_{timestamp}" # Create the main plot plt.figure(figsize=(10, 6)) # Plot each method with error bars plt.errorbar(context_percentages, avg_icl, yerr=std_icl, fmt='o-', label='ICL', capsize=4, linewidth=2) plt.errorbar(context_percentages, avg_lr, yerr=std_lr, fmt='s-', label='LR (PE)', capsize=4, linewidth=2) plt.errorbar(context_percentages, avg_rkhs, yerr=std_rkhs, fmt='^-', label='RKHS (PE)', capsize=4, linewidth=2) plt.errorbar(context_percentages, avg_raw_lr, yerr=std_raw_lr, fmt='d--', label='LR (Raw)', capsize=4, linewidth=2) plt.errorbar(context_percentages, avg_raw_rkhs, yerr=std_raw_rkhs, fmt='v--', label='RKHS (Raw)', capsize=4, linewidth=2) # Add labels and title plt.xlabel('Context Size (% of Total Samples)') plt.ylabel('Accuracy') title_str = f'Classification Performance vs. Context Size\n(Mode: {args.test_mode}, Data: {args.data_type})' plt.title(title_str) plt.grid(True, alpha=0.3) plt.legend(loc='lower right') # Adjust x-axis to show percentages plt.xticks(context_percentages) # Save the figure plt.tight_layout() fig_path = os.path.join(specific_dir, f"{base_filename}_all_methods.png") plt.savefig(fig_path, dpi=300) print(f"Figure saved to {fig_path}") # Create a second plot: Just PE methods vs Raw methods plt.figure(figsize=(10, 6)) # Group PE and Raw methods plt.errorbar(context_percentages, avg_lr, yerr=std_lr, fmt='s-', label='LR (PE)', capsize=4, linewidth=2, color='blue') plt.errorbar(context_percentages, avg_rkhs, yerr=std_rkhs, fmt='^-', label='RKHS (PE)', capsize=4, linewidth=2, color='green') plt.errorbar(context_percentages, avg_raw_lr, yerr=std_raw_lr, fmt='s--', label='LR (Raw)', capsize=4, linewidth=2, color='blue', alpha=0.5) plt.errorbar(context_percentages, avg_raw_rkhs, yerr=std_raw_rkhs, fmt='^--', label='RKHS (Raw)', capsize=4, linewidth=2, color='green', alpha=0.5) # Add labels and title plt.xlabel('Context Size (% of Total Samples)') plt.ylabel('Accuracy') title_str = f'PE Features vs. Raw Features Performance\n(Mode: {args.test_mode}, Data: {args.data_type})' plt.title(title_str) plt.grid(True, alpha=0.3) plt.legend(loc='lower right') # Adjust x-axis to show percentages plt.xticks(context_percentages) # Save the figure plt.tight_layout() fig_path = os.path.join(specific_dir, f"{base_filename}_pe_vs_raw.png") plt.savefig(fig_path, dpi=300) print(f"Figure saved to {fig_path}") # Create a third plot: ICL vs best traditional method plt.figure(figsize=(10, 6)) import matplotlib.pyplot as plt import numpy as np import os import datetime import json def plot_individual_accuracies(args, results, n_samples=100, figure_dir='../figures'): """ Plot individual accuracy metrics across different context sizes. Args: args: Command line arguments containing test_mode, data_type, etc. results: Dictionary containing the test results for each context size n_samples: Total number of samples per graph figure_dir: Directory to save the figures """ # Create timestamp for unique filenames timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") # Create directory structure based on test_mode and data_type specific_dir = os.path.join(figure_dir, f"test_mode_{args.test_mode}", f"data_{args.data_type}", "individual_plots") os.makedirs(specific_dir, exist_ok=True) # Extract context sizes and convert to percentages context_sizes = list(results.keys()) context_percentages = [ctx_size / n_samples * 100 for ctx_size in context_sizes] # Extract average accuracies and standard deviations for each method avg_icl = [sum(results[ctx]['icl_accs']) / len(results[ctx]['icl_accs']) for ctx in context_sizes] avg_lr = [sum(results[ctx]['lr_accs']) / len(results[ctx]['lr_accs']) for ctx in context_sizes] avg_rkhs = [sum(results[ctx]['rkhs_accs']) / len(results[ctx]['rkhs_accs']) for ctx in context_sizes] avg_raw_lr = [sum(results[ctx]['raw_lr_accs']) / len(results[ctx]['raw_lr_accs']) for ctx in context_sizes] avg_raw_rkhs = [sum(results[ctx]['raw_rkhs_accs']) / len(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes] std_icl = [np.std(results[ctx]['icl_accs']) for ctx in context_sizes] std_lr = [np.std(results[ctx]['lr_accs']) for ctx in context_sizes] std_rkhs = [np.std(results[ctx]['rkhs_accs']) for ctx in context_sizes] std_raw_lr = [np.std(results[ctx]['raw_lr_accs']) for ctx in context_sizes] std_raw_rkhs = [np.std(results[ctx]['raw_rkhs_accs']) for ctx in context_sizes] # Define metrics to plot individually metrics = [ {'name': 'ICL', 'avg': avg_icl, 'std': std_icl, 'color': 'red', 'marker': 'o'}, {'name': 'LR (PE)', 'avg': avg_lr, 'std': std_lr, 'color': 'blue', 'marker': 's'}, {'name': 'RKHS (PE)', 'avg': avg_rkhs, 'std': std_rkhs, 'color': 'green', 'marker': '^'}, {'name': 'LR (Raw)', 'avg': avg_raw_lr, 'std': std_raw_lr, 'color': 'purple', 'marker': 'd'}, {'name': 'RKHS (Raw)', 'avg': avg_raw_rkhs, 'std': std_raw_rkhs, 'color': 'orange', 'marker': 'v'} ] # Plot each metric individually for metric in metrics: plt.figure(figsize=(8, 5)) # Plot with error bars plt.errorbar( context_percentages, metric['avg'], yerr=metric['std'], fmt=f"{metric['marker']}-", label=metric['name'], capsize=4, linewidth=2, color=metric['color'] ) # Add labels and title plt.xlabel('Context Size (% of Total Samples)') plt.ylabel('Accuracy') title_str = f"{metric['name']} Accuracy vs. Context Size\n(Mode: {args.test_mode}, Data: {args.data_type})" plt.title(title_str) plt.grid(True, alpha=0.3) # Generate filename safe_name = metric['name'].replace(' ', '_').replace('(', '').replace(')', '') base_filename = f"mode_{args.test_mode}_data_{args.data_type}_samples_{n_samples}_{timestamp}" filename = f"{base_filename}_{safe_name}.png" # Adjust x-axis to show percentages plt.xticks(context_percentages) # Set y-axis range from 0.5 to 1.0 for better comparison plt.ylim([0.5, 1.0]) # Add exact values as text annotations for i, (x, y, std) in enumerate(zip(context_percentages, metric['avg'], metric['std'])): plt.annotate( f"{y:.3f}±{std:.3f}", xy=(x, y), xytext=(0, 10), textcoords='offset points', ha='center', fontsize=8, bbox=dict(boxstyle='round,pad=0.3', fc='white', alpha=0.7) ) # Save the figure plt.tight_layout() fig_path = os.path.join(specific_dir, filename) plt.savefig(fig_path, dpi=300) print(f"Individual {metric['name']} plot saved to {fig_path}") plt.close() # Create a tabular summary and save as CSV import pandas as pd # Create DataFrame summary_data = { 'Context_Size': context_sizes, 'Context_Percentage': context_percentages, 'ICL_Mean': avg_icl, 'ICL_Std': std_icl, 'LR_PE_Mean': avg_lr, 'LR_PE_Std': std_lr, 'RKHS_PE_Mean': avg_rkhs, 'RKHS_PE_Std': std_rkhs, 'LR_Raw_Mean': avg_raw_lr, 'LR_Raw_Std': std_raw_lr, 'RKHS_Raw_Mean': avg_raw_rkhs, 'RKHS_Raw_Std': std_raw_rkhs } df = pd.DataFrame(summary_data) # Save as CSV csv_path = os.path.join(specific_dir, f"{base_filename}_summary.csv") df.to_csv(csv_path, index=False) print(f"Summary data saved to {csv_path}") # Also generate a formatted table as text text_table = "Context Size | ICL | LR (PE) | RKHS (PE) | LR (Raw) | RKHS (Raw)\n" text_table += "------------|-----|---------|-----------|----------|------------\n" for i, ctx in enumerate(context_sizes): text_table += f"{ctx:^12} | {avg_icl[i]:.3f}±{std_icl[i]:.3f} | {avg_lr[i]:.3f}±{std_lr[i]:.3f} | " text_table += f"{avg_rkhs[i]:.3f}±{std_rkhs[i]:.3f} | {avg_raw_lr[i]:.3f}±{std_raw_lr[i]:.3f} | " text_table += f"{avg_raw_rkhs[i]:.3f}±{std_raw_rkhs[i]:.3f}\n" # Save table as txt txt_path = os.path.join(specific_dir, f"{base_filename}_table.txt") with open(txt_path, 'w') as f: f.write(text_table) print(f"Formatted table saved to {txt_path}") return specific_dir